Sed 在匹配给定数量的特定字符的行上

Sed on lines matching a given number of specific character

我的档案:

Nicole,Foo,senior,Lexington
John,Doe,junior,Chicago
John,Fool,True,junior,Detroit
Lara,True,Fool,senior,Miami

我想要的是:当有四个而不是三个逗号时,删除行中的第二个逗号,如下所示:

Nicole,Foo,senior,Lexington
John,Doe,junior,Chicago
John,Fool True,junior,Detroit
Lara,True Fool,senior,Miami

我尝试了什么:

检测带有四个逗号的行:

awk -F, '{print NF-1; next; print [=12=]}' myfile

要删除一行中的第二个逗号:

sed 's/,/ /2' myfile

我仍然不能做的事情: 结合这两个命令,仅将 sed 命令应用于带有 4 个逗号的行。我怀疑它可以用 xargs 以某种方式完成,但我不知道如何用这样的条件语句来处理它。

也许有人可以给我一些指导?

试试这个:

sed '/\([^,]*,\)\{4\}/s/,/ /2' file

当找到 4 个后跟逗号的非逗号字符串序列时,将第二个逗号替换为 space。

在 awk 中(我会使用 sed):

$ awk '
BEGIN { FS=OFS="," }               # separators
NF==5 {                            # for five-fielded records
    for(i=2;i<NF;i++)              # starting from the second
        $i=(i==2?$i " ":"") $(i+1) # append or replace with the next field
    NF=4                           # reduce the field count for those records
}1' file
Nicole,Foo,senior,Lexington
John,Doe,junior,Chicago
John,Fool True,junior,Detroit
Lara,True Fool,senior,Miami

也尝试关注 awk:

awk -F, '{for(i=1;i<=NF;i++){if(NF>4){if(i==2){$i=$i " "$(i+1)};if(i==3){continue}};printf("%s%s",$i,i==NF?"":",");}print ""}'   Input_file

awk -F, '{
for(i=1;i<=NF;i++){
  if(NF>4){
  if(i==2){
    $i=$i " "$(i+1)
  };
  if(i==3){
   continue
  }
  };
  printf("%s%s",$i,i==NF?"":",");
  }
  print ""
}'  Input_file
gawk '/Fool,|True,/{[=10=]=gensub(/,/," ",2)}1' file

Nicole,Foo,senior,Lexington
John,Doe,junior,Chicago
John,Fool True,junior,Detroit
Lara,True Fool,senior,Miami