【问题标题】:Remove sequence of a specific character from the end of a string in Bash从 Bash 中的字符串末尾删除特定字符的序列
【发布时间】:2021-10-11 19:36:17
【问题描述】:

输入:

i="Item1;Item2;Item3;;;;;;;;"

期望的输出:

i="Item1;Item2;Item3"

如何去掉最后几个分号?

我知道使用“sed”的一种方法:

sed 's/;$//'

但是,它只删除最后一个分号。反复运行它似乎并不实际。

【问题讨论】:

    标签: bash sed


    【解决方案1】:

    您不需要为此使用外部实用程序。

    $ input='Item1;Item2;Item3;;;;;;;;'
    $ echo "${input%"${input##*[!;]}"}"
    Item1;Item2;Item3
    

    或者,使用扩展的 glob:

    $ shopt -s extglob
    $ echo "${input%%*(;)}"
    Item1;Item2;Item3
    

    【讨论】:

    • 你保存了一两个叉子,很好
    【解决方案2】:

    你可以使用

    sed 's/;*$//'
    

    这里的重点是在; 之后添加* 量词(即零个或多个),以使正则表达式引擎匹配零个或多个分号。

    同义词sed 命令看起来像

    sed 's/;;*$//'    # POSIX BRE "one ; and then zero or more ;s at the end of string"
    sed 's/;\+$//'    # GNU sed POSIX BRE "one or more semi-colons at the end of string"
    sed -E 's/;+$//'  # POSIX ERE "one or more semi-colons at the end of string"
    

    【讨论】:

      【解决方案3】:

      有条件跳转(t)到标签a

      i="Item1;Item2;Item3;;;;;;;;"
      sed ':a; s/;$//; ta' <<< "$i"  
      

      t label:如果 s/// 在读取最后一个输入行和最后一个 tT 命令后成功替换,则分支到标签。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-07
        • 2017-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多