replacing multiple spaces with comma in unix

2.7k views Asked by At

I have a file with the following data:

1               abcd               hello world               5000

(note: there are 15 spaces between each word and "hello world" is a single entry with one space in between)

I have to replace the 15 spaces with a single comma(,). the single space between "hello and "world" should remain as it is.

I have tried various combinations of sed and tr command but nothing is working.

2

There are 2 answers

0
fedorqui On

This is a job for sed:

$ sed -r 's/ {15}/,/g' file
1,abcd,hello world,5000

or, without the -r flag that allows extended regexp:

$ sed 's/ \{15\}/,/g' file
1,abcd,hello world,5000

This says: get 15 spaces and replace them with a comma. Smaller amount of spaces won't be replaced.

0
Pandrei On

just an improvement really since you already have an correct answer:

This will replace any sequence of at least 2 consecutive spaces with a ','

sed -r 's/ {2,}/,/g' file
1,abcd,hello world,5000

This will allow for "hello world" or any other string which uses a single space as separator and also saves you the trouble of having to make sure you have exactly 15 spaces.