Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace first two whitespace occurrences with a comma using sed

I have a whitespace delimited file with a variable number of entries on each line. I want to replace the first two whitespaces with commas to create a comma delimited file with three columns.

Here's my input:

a b  1 2 3 3 2 1
c d  44 55 66 2355
line http://google.com 100 200 300
ef jh  77 88 99
z y 2 3 33

And here's my desired output:

a,b,1 2 3 3 2 1
c,d,44 55 66 2355
line,http://google.com,100 200 300
ef,jh,77 88 99
z,y,2 3 33

I'm trying to use perl regular expressions in a sed command but I can't quite get it to work. First I try capturing a word, followed by a space, then another word, but that only works for lines 1, 2, and 5:

$ cat test | sed -r 's/(\w)\s+(\w)\s+/\1,\2,/'
a,b,1 2 3 3 2 1
c,d,44 55 66 2355
line http://google.com 100 200 300
ef jh  77 88 99
z,y,2 3 33

I also try capturing whitespace, a word, and then more whitespace, but that gives me the same result:

$ cat test | sed -r 's/\s+(\w)\s+/,\1,/'
a,b,1 2 3 3 2 1
c,d,44 55 66 2355
line http://google.com 100 200 300
ef jh  77 88 99
z,y,2 3 33

I also try doing this with the .? wildcard, but that does something funny to line 4.

$ cat test | sed -r 's/\s+(.?)\s+/,\1,/'
a,b,1 2 3 3 2 1
c,d,44 55 66 2355
line http://google.com 100 200 300
ef jh,,77 88 99
z,y,2 3 33

Any help is much appreciated!

like image 893
Stephen Turner Avatar asked Jul 08 '11 00:07

Stephen Turner


People also ask

How do you replace multiple spaces with commas in Unix?

sed s/ */ /g This will replace any number of spaces with a single space. sed s/ $// This will replace any single space at the end of the line with nothing. sed s/ /,/g This will replace any single space with a single comma.

How do you replace something with sed?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.


1 Answers

How about this:

sed -e 's/\s\+/,/' | sed -e 's/\s\+/,/'

It's probably possible with a single sed command, but this is sure an easy way :)

My output:

a,b,1 2 3 3 2 1
c,d,44 55 66 2355
line,http://google.com,100 200 300
ef,jh,77 88 99
z,y,2 3 33
like image 132
Flimzy Avatar answered Sep 30 '22 14:09

Flimzy