Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove blank spaces with comma in a string in bash shell

Tags:

bash

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
like image 694
user1293997 Avatar asked Apr 02 '12 20:04

user1293997


2 Answers

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.

like image 148
Kent Avatar answered Oct 02 '22 14:10

Kent


Just use sed:

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

or pure BASH way::

echo ${STR1// /,}
like image 36
anubhava Avatar answered Oct 02 '22 16:10

anubhava