【问题标题】:How to trim a string to either specific character in a bash script如何将字符串修剪为bash脚本中的任一特定字符
【发布时间】:2020-11-19 16:48:30
【问题描述】:

我想将字符串从一个字符(最后一个/)修剪为:@,先出现。一个例子是:

https://www.example.com/?client=safari/this-text:not-this:or_this

将被修剪为:

this-text

https://www.example.com/?client=safari/this-text@not-this:or_this 

将被修剪为:

this-text

我知道我可以将 bash 中的文本从特定字符修剪为另一个字符,但是有没有办法从一个字符修剪为 2 个字符中的任何一个?

【问题讨论】:

    标签: string bash trim


    【解决方案1】:

    像这样使用grepgrep -Po '^.*/\K[^:@]*'

    例子:

    echo 'https://www.example.com/?client=safari/this-text:not-this:or_this' | grep -Po '^.*/\K[^:@]*'
    

    或:

    echo 'https://www.example.com/?client=safari/this-text@not-this:or_this' | grep -Po '^.*/\K[^:@]*'
    

    输出:

    this-text
    

    这里,grep 使用以下选项:
    -P:使用 Perl 正则表达式。
    -o:仅打印匹配项,每行 1 个匹配项,而不是整行。

    正则表达式 ^.*/\K[^:@]* 执行以下操作:

    ^.*/ :从字符串的开头 (^) 一直匹配到最后一个斜杠 ('/')。
    \K :假设匹配从这个位置开始。[^:@]* :除:@ 之外的任何字符出现零次或多次(贪婪)。这匹配直到行尾,或者直到下一个:@,以先到者为准。

    另请参阅:
    grep manual

    注意:
    这适用于 GNU grep,可能需要安装,具体取决于您的系统。例如,要在 macOS 上安装 GNU grep,请参阅此答案:https://apple.stackexchange.com/a/357426/329079

    【讨论】:

    • 嗯,我在尝试这个时遇到了 grep 使用错误。
    • @ryan grep -P 需要 GNU grep,如果你在 macOS 上,默认情况下你不会有。
    • @ryan 我编辑了答案并添加了重新安装 GNU grep 的注释。
    【解决方案2】:

    带有一点 Bash 功能:

    trim() {
        local str=${1##*/}
        printf '%s\n' "${str%%[:@]*}"
    }
    
    

    这首先修剪所有内容,包括最后一个 /,然后修剪从第一次出现的 :@ 开始的所有内容。

    使用中:

    $ trim 'https://www.example.com/?client=safari/this-text:not-this:or_this'
    this-text
    $ trim 'https://www.example.com/?client=safari/this-text@not-this:or_this'
    this-text
    

    【讨论】:

    • 此答案仅使用 Bash 内置函数,因此避免了有利于性能的 fork()+exec() 系统调用。 (+1)
    【解决方案3】:

    另一种方法是使用sed:sed -e 's,^.*/,,' -e 's,[:@].*$,,'

    第一个 -e 命令 (s/regex/replacement/) 从开头删除文本到最后一个 /,然后第二个 -e:@ 删除到文本末尾。

    echo 'https://www.example.com/?client=safari/this-text:not-this:or_this' | sed -e 's,^.*/,,' -e 's,[:@].*$,,'
    this-text
    

    【讨论】:

      猜你喜欢
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      • 2014-11-27
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 2021-04-06
      相关资源
      最近更新 更多