bash 在bash shell中用逗号删除字符串中的空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9983566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove blank spaces with comma in a string in bash shell
提问by user1293997
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
回答by Mat
Without using external tools:
不使用外部工具:
echo ${STR1// /,}
Demo:
演示:
$ STR1="This is a string"
$ echo ${STR1// /,}
This,is,a,string
See bash: Manipulating strings.
请参阅bash:操作字符串。
回答by anubhava
Just use sed:
只需使用 sed:
echo $STR1 | sed 's/ /,/g'
or pure BASH way::
或纯 BASH 方式::
echo ${STR1// /,}
回答by Kent
kent$ echo "STR1=This is a string"|awk -v OFS="," '='
STR1=This,is,a,string
Note:
笔记:
if there are continued blanks, they would be replaced with a single comma. as example above shows.
如果有连续的空格,它们将替换为一个逗号。如上例所示。
回答by potong
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
回答by shellter
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
[[:space:]]+` to work as well.
我使用的是非标准 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:]]+”。
回答by Teja
STR1=`echo $STR1 | sed 's/ /,/g'`