【问题标题】:Grep for matching pattern but exclude particular string用于匹配模式但排除特定字符串的 Grep
【发布时间】:2019-05-16 02:39:09
【问题描述】:

我有一个包含各种日志行的文件,我想 grep 获取一个模式,但在 message:com.mycompany.excluded 时排除,所以基本上应该返回以下内容:

"The log found this message blah, message:com.blahblah"
"The log found this message blah2, message:com.blahblah2"
"The log found this message foobar, message:com.mycompany"
"The log found this message blah, message:com.mycompany.included"

但不是:

 "The log found this message blah, message:com.mycompany.excluded"

我正在使用这种模式,但它不适用于排除 com.mycompany.excluded

grep "The log found this message.*message:.*" "mylogs.txt"

【问题讨论】:

  • 您应该在示例中包含一些与 The log found this message.*message:.* 不匹配的行,以便更清楚地表明您确实需要匹配该正则表达式。并根据您的示例输入添加预期输出。

标签: grep pattern-matching


【解决方案1】:
awk '/The log found this message.*message:/ && !/com.mycompany.excluded/' "mylogs.txt"

有多种方法可以使它更健壮,但可能不是必需的(取决于日志文件的其余部分)。

【讨论】:

    【解决方案2】:

    你想要的是sed,而不是grep

    sed -i .bak 's/^.*excluded//' mylogs.txt

    -i .bak 使用扩展名 .bak 创建原始文件的备份;这将留下mylogs.txtmylogs.txt.bakmylogs.txt 删除不需要的行。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 2013-03-22
      • 1970-01-01
      • 2014-09-07
      相关资源
      最近更新 更多