shell bash中如何去掉字符串中空格?

如果你经常写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}")="

file

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-
Supervisor 的 Event & Listener进程监控告警
Stable Diffusion公司开源大语言模型StableLM来了!
标签:

发表我的评论

电子邮件地址不会被公开。 必填项已用*标注

23 + 56 =

ajax-loader