0

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Prashanth
  • 87
  • 1
  • 2
  • 6
  • Possible duplicate of [Replace multiple consecutive white spaces with one comma in Unix](https://stackoverflow.com/q/23106621/608639) – jww May 26 '19 at 22:45

2 Answers2

5

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
1

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.

Pandrei
  • 4,843
  • 3
  • 27
  • 44