代码之家  ›  专栏  ›  技术社区  ›  ΩlostA

regex&sed:如何在正好包含9个逗号的字符串中取消第一个和第二个逗号?

  •  0
  • ΩlostA  · 技术社区  · 6 年前

    我想在包含10个且只有10个逗号(11个字段)的字符串中抑制前两个逗号。我不想删除9个逗号行的逗号。

    我试过这个:

    sed '/^\([^,]*,\)\{10\}[^,]*$/s/,//1;s/,//2'  
    

    但它会删除逗号,即使在包含少于10个逗号的句子中,它也会删除第一个和第三个逗号。

    例子:

    DE, LAEIES,Vlzgstraat, 16,2260,NIJLEN,BELGIË,06346641,0636641,NL
    Leonarfdsdy Dandfiel, Ingendfdfdfieur - Leon.ing,rombach, Hinderusen, 485,47580,SANKT VITH,BELGIQUE,0442345,2058560,FR
    

    预期结果:

    DE, LAEIES,Vlzgstraat, 16,2260,NIJLEN,BELGIË,06346641,0636641,NL
    Leonarfdsdy Dandfiel Ingendfdfdfieur - Leon.ing rombach, Hinderusen, 485,47580,SANKT VITH,BELGIQUE,0442345,2058560,FR
    
    3 回复  |  直到 6 年前
        1
  •  2
  •   Tyl    6 年前

    我猜您使用的是MacOS SED/BSD SED,请尝试:

    sed -e '/^\([^,]*,\)\{10\}[^,]*$/s/,//; tLB' -e 'b' -e ':LB' -e 's/,/ /'
    

    我用过 --posix 要模拟,但不确定它是否适用于您的操作系统:

    $ cat file
    DE, LAEIES,Vlzgstraat, 16,2260,NIJLEN,BELGI?,06346641,0636641,NL
    Leonarfdsdy Dandfiel, Ingendfdfdfieur - Leon.ing,rombach, Hinderusen, 485,47580,SANKT VITH,BELGIQUE,0442345,2058560,FR
    
    $ sed --posix -e '/^\([^,]*,\)\{10\}[^,]*$/s/,//; tLB' -e 'b' -e ':LB' -e 's/,/ /' file
    DE, LAEIES,Vlzgstraat, 16,2260,NIJLEN,BELGI?,06346641,0636641,NL
    Leonarfdsdy Dandfiel Ingendfdfdfieur - Leon.ing rombach, Hinderusen, 485,47580,SANKT VITH,BELGIQUE,0442345,2058560,FR
    

    注意第二个 s 命令,我将替换为 space ,因为 Leon.ing,rombah 里面没有空间,简单的剥掉 , 将成为 Leon.ingrombach .

    这也可能奏效:

    sed -e '/^\([^,]*,\)\{10\}[^,]*$/{' -e 's/,/ /' -e 's/,/ /}'
    

    顺便说一句,我认为现在是您开始使用GNU SED的时候了:

    brew install gnu-sed
    ln -s /usr/local/bin/gsed /usr/local/bin/sed
    

    这个问题也更容易使用 awk 而是:

    awk -F, 'NF==11{sub(",","");sub(","," ")}1' file
    

    仅当有11个逗号分隔的字段时才替换。

        2
  •  3
  •   Wiktor Stribiżew    6 年前

    您可以使用

    sed -E 's/^([^,]*),([^,]*),([^,]*)((,[^,]*){7})$/\1\2\3\4/'
    

    细节

    • ^ -行首
    • ([^,]*) -第1组 \1 ):除 ,
    • ,([^,]*) - , 和第2组( \2 )匹配除 ,
    • ,([^,] *) - , 和第3组( \3 )匹配除 ,
    • ((,[^,]*){7}) -出现7次 , 后接除 ,
    • $ -字符串结尾。

    online sed demo :

    s="Leonarfdsdy Dandfiel, Ingendfdfdfieur - Leon.inrombach, Hinderusen, 485,47580,SANKT VITH,BELGIQUE,0442345,2058560,FR"
    sed -E 's/^([^,]*),([^,]*),([^,]*)((,[^,]*){7})$/\1\2\3\4/' <<< "$s"
    # => Leonarfdsdy Dandfiel Ingendfdfdfieur - Leon.inrombach Hinderusen, 485,47580,SANKT VITH,BELGIQUE,0442345,2058560,FR
    
        3
  •  0
  •   potong    6 年前

    这可能适用于您(GNU SED):

    sed 's/,/&/9;T;s//&/10;t;s///;s///' file
    

    如果没有至少9个 , 的离开。如果有10个或更多 , 的离开。否则移除前2个 , s。

    另一种选择:

    sed -r 's/^([^,]*),([^,]*),(([^,]*,){7}[^,]*)$/\1\2\3/' file