[英]Remove blank spaces with comma in a string in bash shell
I would like to replace blank spaces/white spaces in a string with commas. 我想用逗号替换字符串中的空格/空格。
STR1=This is a string
to 至
STR1=This,is,a,string
Without using external tools: 不使用外部工具:
echo ${STR1// /,}
Demo: 演示:
$ STR1="This is a string"
$ echo ${STR1// /,}
This,is,a,string
See bash: Manipulating strings . 请参阅bash:操作字符串 。
Just use sed: 只需使用sed:
echo $STR1 | sed 's/ /,/g'
or pure BASH way:: 或纯BASH方式::
echo ${STR1// /,}
kent$ echo "STR1=This is a string"|awk -v OFS="," '$1=$1'
STR1=This,is,a,string
Note: 注意:
if there are continued blanks, they would be replaced with a single comma. 如果有继续空白,它们将被替换为一个逗号。 as example above shows.
如上例所示。
How about 怎么样
STR1="This is a string"
StrFix="$( echo "$STR1" | sed 's/[[:space:]]/,/g')"
echo "$StrFix"
**output**
This,is,a,string
If you have multiple adjacent spaces in your string and what to reduce them to just 1 comma, then change the sed
to 如果您的字符串中有多个相邻的空格以及将它们简化为1个逗号的内容,则将
sed
更改为
STR1="This is a string"
StrFix="$( echo "$STR1" | sed 's/[[:space:]][[:space:]]*/,/g')"
echo "$StrFix"
**output**
This,is,a,string
I'm using a non-standard sed, and so have used ``[[:space:]][[:space:]]* to indicate one or more "white-space" characters (including tabs, VT, maybe a few others). In a modern sed, I would expect
我使用的是非标准的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
to indicate one or more "white-space" characters (including tabs, VT, maybe a few others). In a modern sed, I would expect
[[:space:]]+` to work as well. to indicate one or more "white-space" characters (including tabs, VT, maybe a few others). In a modern sed, I would expect
[[:space:]] +`也能正常工作。
This might work for you: 这可能对你有用:
echo 'STR1=This is a string' | sed 'y/ /,/'
STR1=This,is,a,string
or: 要么:
echo 'STR1=This is a string' | tr ' ' ','
STR1=This,is,a,string
STR1=`echo $STR1 | sed 's/ /,/g'`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.