Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace space with comma using sed?

I would like to replace the empty space between each and every field with comma delimiter.Could someone let me know how can I do this.I tried the below command but it doesn't work.thanks.

My command: :%s//,/   53 51097 310780 1 56 260 1925 1 68 51282 278770 1 77 46903 281485 1 82 475 2600 1 84 433 3395 1 96 212 1545 1 163 373819 1006375 1 204 36917 117195 1 
like image 835
Teja Avatar asked Nov 24 '12 06:11

Teja


People also ask

How do you replace multiple spaces with commas in Unix?

Simple SED commands are: 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 special characters in sed?

You need to escape the special characters with a backslash \ in front of the special character. For your case, escape every special character with backslash \ .


2 Answers

If you are talking about sed, this works:

sed -e "s/ /,/g" < a.txt 

In vim, use same regex to replace:

s/ /,/g 
like image 164
mvp Avatar answered Sep 23 '22 11:09

mvp


Inside vim, you want to type when in normal (command) mode:

:%s/ /,/g 

On the terminal prompt, you can use sed to perform this on a file:

sed -i 's/\ /,/g' input_file 

Note: the -i option to sed means "in-place edit", as in that it will modify the input file.

like image 25
sampson-chen Avatar answered Sep 21 '22 11:09

sampson-chen