【问题标题】:How to format the output of a grep with a regex pattern to match between a string and character如何使用正则表达式模式格式化 grep 的输出以匹配字符串和字符
【发布时间】:2016-11-18 15:46:26
【问题描述】:

我一直在研究一个 bash 脚本,该脚本将字符串从 logFile 中的出现 grep 到 outputFile 以监视其频率。我想进一步过滤它并使用该 grep 的结果将字符串的一部分格式化为我的最终结果。

目前我的grep如下获取我需要的logFile输出部分:

grep -n -A 1 "No entry for this particular code type" logFile.txt >> outputfile.txt

这会得到以该字符串开头的完整行,如下所示,代码类型的值在整个日志中不断变化: “此特定代码类型没有条目,代码类型:001123。”等等

我想解析从 grep 输出的上述结果行,并仅检索字符串“代码类型:”和字符“。”之间的值。 这会给我像 001123 之类的值

我一直在网上寻找解决方案,但我尝试过的都没有解决。任何建议将不胜感激。

【问题讨论】:

    标签: regex bash grep


    【解决方案1】:

    您可以使用sed 使用另一个正则表达式提取数字:

    cat outputfile.txt | sed 's/.*code type: \(.*\)\./\1/'
    

    \1 引用表达式的\(.*\) 部分的内容(第一个match group)。

    【讨论】:

      【解决方案2】:

      您可以使用 bash 内置 regEx 支持来做到这一点。 假设您将输出捕获在 bash 变量中

      $ myString="No entry for this particular code type, code type: 001123."
      $ [[ $myString =~ code\ type:(.*). ]] && subString="${BASH_REMATCH[1]}"
      $
      $ printf "%s\n" "$subString"
      001123
      

      (或)如果您可以再次使用grep 管道进行regEx 捕获,请执行

      $ <first_grep_command> | grep -Po "code type: \K.*(?=.)"
      001123
      

      -P 标志仅支持 perl 样式正则表达式匹配,-o 仅返回匹配字符串。

      【讨论】:

        【解决方案3】:

        这个直接在我的shell中工作:

        echo "No entry for this particular code type, code type: 001123." |grep -Po '[0-9]*'
        

        意味着这个可以在没有太多管道的情况下在你的情况下工作:

        grep -Po '[0-9]*' logfile.txt >>outputfile.txt
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多