使用sed用逗号替换前两个空格 [英] Replace first two whitespace occurrences with a comma using sed

查看:289
本文介绍了使用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.

这里是我的输入:

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

这里是我想要的输出:

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


b $ b

我试图在sed命令中使用perl正则表达式,但我不能让它工作。首先我尝试捕获一个单词,然后是空格,然后是另一个单词,但只适用于第1,2和5行:

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

我也尝试这样做。通配符,但这对第4行很有趣。

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

推荐答案

如何做到这一点:



How about this:

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

单个sed命令,但这是一个简单的方法:)

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

我的输出:

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

这篇关于使用sed用逗号替换前两个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆