【问题标题】:Extract token after particular substring in bash在bash中的特定子字符串之后提取令牌
【发布时间】:2014-05-22 23:27:09
【问题描述】:

假设我在一个包含多行的 bash 脚本中有一个字符串变量:

blah blah blah
...
...
an interesting parameter: 12345 some other useless stuff...
...
...

我想从这个字符串中提取 12345。我试图寻找使用“一个有趣的参数:”作为“分隔符”的方法,但我无法让它发挥作用。有没有一种干净的方法可以做到这一点?

【问题讨论】:

    标签: bash


    【解决方案1】:

    bash 支持正则表达式匹配,无需使用外部程序。

    $ str='
    blah blah blah
    ...
    ...
    an interesting parameter: 12345 some other useless stuff...
    ...
    ...'
    $ [[ $str =~ an\ interesting\ parameter:\ ([[:digit:]]+) ]]
    
    $ echo ${BASH_REMATCH[1]}
    12345
    

    数组BASH_REMATCH 包含元素 0 中的完整匹配项和后续元素中捕获的子组(按从左到右的顺序)。

    【讨论】:

    • 绝对比外部程序好! +1
    【解决方案2】:

    试试这个:

    grep -Po 'an interesting parameter:\s*\K\S*'
    

    【讨论】:

      【解决方案3】:

      你可以使用 sed:

      sed -n 's/.*an interesting parameter: \([0-9]\+\).*/\1/p' <<< "$string"
      

      【讨论】:

        【解决方案4】:

        使用正则表达式的纯 Bash:

        $ a='blah blah blah
        > ...
        > ...
        > an interesting parameter: 12345 some other useless stuff...
        > ...
        > ...'
        $ [[ $a =~  "an interesting parameter: "([[:digit:]]+) ]] && echo "${BASH_REMATCH[1]}"
        12345
        

        使用参数扩展的纯 Bash:

        $ t=${a#*an interesting parameter: }
        $ echo "$t"
        12345 some other useless stuff...
        ...
        ...
        $ u=${t%% *}
        $ echo "$u"
        12345
        

        【讨论】:

          【解决方案5】:

          试试这个sed 命令,

          sed -n '/interesting parameter/ s/.*parameter: \([0-9]\+\) .*/\1/p' file
          

          对于你的情况,

          sed -n '/interesting parameter/ s/.*parameter: \([0-9]\+\) .*/\1/p' <<< "$string"
          

          【讨论】:

            【解决方案6】:

            试试这个:

            cat content | grep "an interesting parameter: " | awk '{print $4}'

            【讨论】:

              猜你喜欢
              • 2020-04-17
              • 2015-06-06
              • 2022-08-10
              • 1970-01-01
              • 2021-10-30
              • 1970-01-01
              • 1970-01-01
              • 2021-01-21
              • 2015-02-02
              相关资源
              最近更新 更多