简体   繁体   English

使用 sed 将每隔一个逗号替换为空格

[英]Replace every second comma with space using sed

I am looking to replace every second comma on every line of a text file with a space using sed or awk in the Linux terminal.我希望在 Linux 终端中使用 sed 或 awk 将文本文件每一行的第二个逗号替换为空格。 The file looks like:该文件如下所示:

1,2,5,32,67,28,40,30...
2,4,90,18,22,40,20,15....

and I want a specific software input file format:我想要一个特定的软件输入文件格式:

1,2 5,32 67,28 40,30
2,4 90,18 22,40 20,15...

I tried我试过了

sed -r 's/([^,]+ +[^,]) +/\1\s/g' Test.txt > Test2.txt

but this did not work.但这没有用。 Any help would be much appreciated.任何帮助将非常感激。

Using sed使用sed

$ sed 's/\(.\{3\}\),/\1 /g' input_file
1,2 5,32 67,28 40,30...
2,4 90,18 22,40 20,15....

You can use您可以使用

sed -E 's/(,[^,]*),/\1 /g' file > newfile

Details :详情

  • (,[^,]*), matches and captures into Group 1 a comma and then any zero or more chars other than a comma, and then matches a comma (,[^,]*),匹配并捕获第 1 组一个逗号,然后是逗号以外的任何零个或多个字符,然后匹配一个逗号
  • \1 replaces the match with Group 1 value and adds a space right after. \1用第 1 组值替换匹配项并在其后添加一个空格。

The -E option enables POSIX ERE regex syntax. -E选项启用 POSIX ERE 正则表达式语法。

See the online demo :请参阅在线演示

#!/bin/bash
s='1,2,5,32,67,28,40,30...
2,4,90,18,22,40,20,15....'
sed -E 's/(,[^,]*),/\1 /g' <<< "$s"

Output: Output:

1,2 5,32 67,28 40,30...
2,4 90,18 22,40 20,15....

slighly verbose awk-based solution that's confirmed working on gawk, mawk-1, mawk-1.996, and nawk:确认在 gawk、mawk-1、mawk-1.996 和 nawk 上工作的基于 awk 的稍微冗长的解决方案:

[g/m/n]awk 'sub("^"(_="[^,]+,")_,"&"(_="\3\21"))sub(","_," ")_'

I picked \032\021 as a safer choice than merely going with subsep, since the chance of this combo appearing is rather low.我选择\032\021作为比仅仅使用 subsep 更安全的选择,因为这个组合出现的机会相当低。 A more concise solution would be like一个更简洁的解决方案就像

 mawk 'sub("^"(_="[^,]+,")_,"&\5")sub(",\5"," ")_'

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

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