如果你经常写bash脚本,习惯用命令行操作或者命令来处理一些文本文件,不可避免就会遇到需要去掉字符串空格的场景。在bash中可以使用sed命令、awk命令、cut命令、tr命令来去掉空格。
文章目录
去掉制表符和空格
output="= This is a test ="
echo "=$(sed -e 's/^[ \t]*//' -e 's/\ *$//g'<<<"${output}")="
## more readable syntax #
echo "=$(sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'<<<"${output}")="
output=" This is a test "
echo "=${output}="
## Use awk to trim leading and trailing whitespace
echo "${output}" | awk '{gsub(/^ +| +$/,"")} {print "=" $0 "="}'
echo "GNU \ Linux" | tr -s ' '
output=" This is a test "
output=${output// /}
echo $output |cut -d " " --output-delimiter="" -f 1-