Remove spaces with a comma in a string in a bash shell

I would like to replace spaces / spaces in a string with commas.

STR1=This is a string 

to

 STR1=This,is,a,string 
+7
source share
6 answers

Without using external tools:

 echo ${STR1// /,} 

Demo:

 $ STR1="This is a string" $ echo ${STR1// /,} This,is,a,string 

See bash: Manipulating strings .

+15
source

Just use sed:

 echo $STR1 | sed 's/ /,/g' 

or pure BASH path ::

 echo ${STR1// /,} 
+10
source
 kent$ echo "STR1=This is a string"|awk -v OFS="," '$1=$1' STR1=This,is,a,string 

Note:

if spaces are continued, they will be replaced by one comma. as shown above.

+5
source

What about

 STR1="This is a string" StrFix="$( echo "$STR1" | sed 's/[[:space:]]/,/g')" echo "$StrFix" **output** This,is,a,string 

If there are several contiguous spaces in your line and that they should be reduced to 1 comma, change sed to

 STR1="This is a string" StrFix="$( echo "$STR1" | sed 's/[[:space:]][[:space:]]*/,/g')" echo "$StrFix" **output** This,is,a,string 

I use custom sed and therefore 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 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 the same.

+2
source

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 
+1
source
 STR1=`echo $STR1 | sed 's/ /,/g'` 
0
source

All Articles