使用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