简体   繁体   English

如何使用sed用逗号替换空格?

[英]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 ,那么它可以工作:

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

In vim , use same regex to replace: vim ,使用相同的正则表达式替换:

s/ /,/g

Inside vim , you want to type when in normal (command) mode: vim内部,要在普通(命令)模式下键入:

:%s/ /,/g

On the terminal prompt, you can use sed to perform this on a file: 在终端提示下,您可以使用sed在文件上执行此操作:

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. 注意: sed-i选项表示“就地编辑”,因为它将修改输入文件。

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

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). 在Cygwin终端(最小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) 在Linux上,使用以下代码进行测试(它将用逗号替换空格)

 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 PS:test是您要使用的文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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