简体   繁体   中英

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

If you are talking about sed , this works:

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

In vim , use same regex to replace:

s/ /,/g

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.

我知道这不完全是您要的内容,但是,用换行符替换逗号,效果很好:

tr , '\n' < file

尝试以下命令,它应该为您解决。

sed "s/\s/,/g" orignalFive.csv > editedFinal.csv

If you want the output on terminal then,

$sed 's/ /,/g' filename.txt

But if you want to edit the file itself ie if you want to replace space with the comma in the file then,

$sed -i 's/ /,/g' filename.txt

I just confirmed that:

cat file.txt | sed "s/\s/,/g"

successfully replaces spaces with commas in Cygwin terminals (mintty 2.9.0). None of the other samples worked for me.

IF your data includes an arbitrary sequence of blank characters (tab, space), and you want to replace each sequence with one comma, use the following:

sed 's/[\t ]+/,/g' input_file

or

sed -r 's/[[:blank:]]+/,/g' input_file

If you want to replace sequence of space characters, which includes other characters such as carriage return and backspace, etc, then use the following:

sed -r 's/[[:space:]]+/,/g' input_file

On Linux use below to test (it would replace the whitespaces with comma)

 sed 's/\s/,/g' /tmp/test.txt | head

later you can take the output into the file using below command:

sed 's/\s/,/g' /tmp/test.txt > /tmp/test_final.txt

PS: test is the file which you want to use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM