我想用逗号替换字符串中的空格/空格。
STR1=This is a string
到
STR1=This,is,a,string
答案 0 :(得分:16)
不使用外部工具:
echo ${STR1// /,}
演示:
$ STR1="This is a string"
$ echo ${STR1// /,}
This,is,a,string
答案 1 :(得分:12)
只需使用sed:
echo $STR1 | sed 's/ /,/g'
或纯BASH方式::
echo ${STR1// /,}
答案 2 :(得分:6)
kent$ echo "STR1=This is a string"|awk -v OFS="," '$1=$1'
STR1=This,is,a,string
注意:
如果有持续的空白,则会用一个逗号替换它们。如上例所示。
答案 3 :(得分:2)
怎么样
STR1="This is a string"
StrFix="$( echo "$STR1" | sed 's/[[:space:]]/,/g')"
echo "$StrFix"
**output**
This,is,a,string
如果您的字符串中有多个相邻的空格以及将它们简化为1个逗号的内容,请将sed
更改为
STR1="This is a string"
StrFix="$( echo "$STR1" | sed 's/[[:space:]][[:space:]]*/,/g')"
echo "$StrFix"
**output**
This,is,a,string
我使用的是非标准的sed,因此使用了``[[:space:]] [[:space:]] * to indicate one or more "white-space" characters (including tabs, VT, maybe a few others). In a modern sed, I would expect
[[:space:]] +`工作也好。
答案 4 :(得分:2)
这可能对您有用:
echo 'STR1=This is a string' | sed 'y/ /,/'
STR1=This,is,a,string
或:
echo 'STR1=This is a string' | tr ' ' ','
STR1=This,is,a,string
答案 5 :(得分:0)
STR1=`echo $STR1 | sed 's/ /,/g'`