shell bash中如何去掉字符串中空格?
嘻嘻发布于2023-04-25
最后更新于2023年4月25日
浏览如果你经常写bash脚本,习惯用命令行操作或者命令来处理一些文本文件,不可避免就会遇到需要去掉字符串空格的场景。在bash中可以使用sed命令、awk命令、cut命令、tr命令来去掉空格。
sed命令去掉空格
去掉制表符和空格
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}")="
AWK命令去掉空格
output=" This is a test "
echo "=${output}="
## Use awk to trim leading and trailing whitespace
echo "${output}" | awk '{gsub(/^ +| +$/,"")} {print "=" $0 "="}'
TR去掉空格
echo "GNU \ Linux" | tr -s ' '
字符串替换掉空格
output=" This is a test "
output=${output// /}
cut去掉空格
echo $output |cut -d " " --output-delimiter="" -f 1-