16

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 
1
  • 4
    Should 2 consecutive spaces be replaced by one comma? Commented Apr 2, 2012 at 21:30

6 Answers 6

29

Without using external tools:

echo ${STR1// /,} 

Demo:

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

See bash: Manipulating strings.

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to force multiple spaces to be translated into a single comma (without turning to a tool like awk)?
@Kyle: if you have extglob on, you can do something like ${STR1//+( )/,}.
perfect solution. Elegant.
16

Just use sed:

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

or a pure BASH substitution:

echo "${STR1// /,}" 

Comments

14
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.

2 Comments

This is almost certainly the answer that most people who visit this question are looking for, rather than variations on replacing a series of spaces with a series of commas.
I think this should be the best answer as the top answer also putting comma at the end if there is blank space which is not good.
3

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 

Comments

3

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

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.

Comments

0
STR1=`echo $STR1 | sed 's/ /,/g'` 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.