【问题标题】:Remove ] from string based on whether it used as index根据是否用作索引从字符串中删除 ]
【发布时间】:2012-11-16 13:12:17
【问题描述】:

尝试使用 sed(在 bash 脚本中)进行一些子字符串编辑

string1=randomthing0]
string2=otherthing[15]}]
string3=reallyotherthing[5]]

目的是当 ]s 不像第二个那样用作索引类型时删除它。 输出应该是

string1=randomthing0
string2=otherthing[15]}
string3=reallyotherthing[5]

【问题讨论】:

    标签: bash sed


    【解决方案1】:

    这对我有用:

    s/\[\([^]]\+\)\]/@B@\1@E@/g
    s/\]//g
    s/@B@/[/g
    s/@E@/]/g
    

    它首先将所有[...] 替换为@B@...@E@,i.t.唯一剩下的] 是非平衡的。然后,它只是删除它们并将@-strings 替换回来。

    小心:您的输入不应包含@-strings。

    【讨论】:

    • 您可以处理的方法是将命令包装在sed 's/@/@A/g' | ... script ... | sed 's/@A/@/g' 中,因此在脚本中您可以使用@B、@C 等来表示您喜欢的任何内容,并且您知道那些不能出现在您的脚本获得的输入中,因为由于第一个 sed,您原始输入中的每个 @ 后面都有一个 A。
    • 请注意,上面的脚本对于 the [ array[7] 之类的文本可能不会像您希望的那样运行,因为第一个 sed 命令将匹配 [ array[7] 而不是 [7]。如果这是个问题,请将[^]] 更改为[^][]
    【解决方案2】:

    如果 awk 也被接受,请检查下面的 awk 解决方案:

    awk  'BEGIN{OFS=FS=""}{ for(i=1;i<=NF;i++){
            s+=$i=="["?1:0; 
            e+=$i=="]"?1:0;            
            if(e>s){$i="";e--} } 
            s=e=0; print $0; }' file
    

    注意

    • 上面的脚本不够通用。它只删除不平衡的"]",这意味着foo[a[b[c]不会被修改
    • 如果有不平衡的],无论是否在行尾,都会被删除。所以foo[x]bar]blah 会变成foo[x]barblah

    一个例子可以更好地解释它:(我在你的输入中添加了两行)

    #in my new lines(1,2) all "]"s surrounded with * should be removed
    kent$  cat a.txt  
    stringx=randomthi[foo]bar*]*xx*]*
    stringy=random[f]x*]*bar[b]*]*blah
    string1=randomthing0]
    string2=otherthing[15]}]
    string3=reallyotherthing[5]]
    
    kent$  awk  'BEGIN{OFS=FS=""}{ for(i=1;i<=NF;i++){
            s+=$i=="["?1:0;
            e+=$i=="]"?1:0;
            if(e>s){$i="";e--} } 
            s=e=0; print $0; }' a.txt
    stringx=randomthi[foo]bar**xx**
    stringy=random[f]x**bar[b]**blah
    string1=randomthing0
    string2=otherthing[15]}
    string3=reallyotherthing[5]
    

    希望对你有帮助

    【讨论】:

      【解决方案3】:
      sed 's/\([^\[0-9]\)\([0-9\]*\)\]/\1\2/'
      

      这会删除任何前面有不在 [ 或 0-9 中的内容后跟零个或多个 0-9 字符的 ]。

      【讨论】:

        【解决方案4】:

        这可能对你有用(GNU sed):

        sed -r 's/([^][]*(\[[^]]*\][^][]*)*)\]/\1/g' file
        

        【讨论】:

          猜你喜欢
          • 2019-12-22
          • 2019-12-02
          • 2020-01-15
          • 1970-01-01
          • 1970-01-01
          • 2023-01-07
          • 2022-11-14
          • 2015-04-22
          • 2019-12-04
          相关资源
          最近更新 更多