【问题标题】:Fail to exclude words from grep command无法从 grep 命令中排除单词
【发布时间】:2018-04-27 12:55:12
【问题描述】:

为了过滤日志文件中的错误,我有一个类似的命令

sudo grep -R --color=always -ri "err" *.log | grep -v "terry"

但输出不是我想要的。我仍然看到像

这样的线条

mail.log:Mar 27 10:31:44 (removed) postfix/smtp[5449]: 4EB0822348: to=, relay=(removed), delay=6.6, delays=0.55/0.02/3.4/2.6, dsn =2.0.0,状态=已发送(250 OK id=1csFlH-00010k-6T)

当我从其中排除“terry”时,为什么该行出现在这里?

【问题讨论】:

  • 什么平台?视窗?请提供输入示例。确保\n 明显
  • ubuntu 16.10 - 要重现,请将上面的 mail.log 行粘贴到 mail.log 文件中并运行上面的 grep 命令...它不应该显示它

标签: linux bash grep


【解决方案1】:

您的“--color=always”是您仍然获得结果的原因。请记住,管道将一个程序的标准输出发送到另一个程序的标准输入。您的第一个 grep 命令的输出是输出颜色。为了将颜色输出到屏幕,您必须将颜色代码发送到外壳。为了让 shell 将这些字符解释为颜色,它必须使用如下转义码:

echo -e "This is \e[31mRed"

“Red”这个词在回显时会变成红色。所以 grep 将转义字符发送到第二个 grep 命令。通过将您的第一个 grep 命令重定向到一个文件然后检查该文件来亲自尝试一下。

grep -R --color=always -ri 'err' /tmp/log/syslog > /tmp/log/syslog2

现在在文本编辑器中打开文件(不要将文件拖出,因为您只会看到颜色)。

ar 26 10:30:59 zipmaster07 cinnamon-screensaver-dialog: pam_ecryptfs: seteuid ^[[01;31m^[[Kerr^[[m^[[Kor
Mar 26 14:27:19 zipmaster07 cinnamon-screensaver-dialog: pam_ecryptfs: seteuid ^[[01;31m^[[Kerr^[[m^[[Kor
t^[[01;31m^[[Kerr^[[m^[[Ky was here with an ^[[01;31m^[[Kerr^[[m^[[Kor.
mail.log:Mar 27 10:31:44 (removed) postfix/smtp[5449]: 4EB0822348: to=<t^[[01;31m^[[Kerr^[[m^[[Ky@(removed

“terry@....”这行不再是 terry,它是“t^[[01;31m^[[Kerr^....”,并且“terry”的反向匹配不等于“ t^[[01;31m^[[Kerr^....”,因此 grep 包含它。

您需要删除颜色选项。

jschaeffer@zipmaster07 ~ $ grep -R -ri 'err' /tmp/log/sys2.log
pam_ecryptfs: seteuid err
pam_ecryptfs: seteuid err
terry was here with an error.
mail.log:Mar 27 10:31:44 (removed) postfix/smtp[5449]: 4EB0822348: to=<terry@(removed)>, relay=(removed), delay=6.6, delays=0.55/0.02/3.4/2.6, dsn=2.0.0, status=sent (250 OK id=1csFlH-00010k-6T)

现在使用第二个 grep。

schaeffer@zipmaster07 ~ $ grep -R -ri 'err' /tmp/log/sys2.log | grep -v terry
pam_ecryptfs: seteuid err
pam_ecryptfs: seteuid err

希望这一切都有意义。

【讨论】:

  • 啊,这些颜色值,有道理!感谢您指出这些。
  • 但是......我仍然想用颜色突出匹配。否则我的眼睛扫描这么多日志行会太痛苦。有什么技巧可以让它和--color=always一起工作吗?
  • 我确信可以编写一个包含“err”但不包含“terry”的正则表达式,我现在想不出。使用单个正则表达式,您可以使用单个 grep 命令。同时,只需翻转 grep 语句:grep -v terry /tmp/log/sys2.log | grep -i --color=always 'err'
  • hmmm,递归出现了一个新问题:grep -v terry -R /tmp/log/*.log | grep -i --color=always 'err' 似乎不是递归的,仍然只显示第一个文件夹中的那些条目。
  • 递归选项不起作用,因为您没有指定目录(除非 /tmp/log 下以 .log 结尾的任何条目是实际目录而不是文件)。首先没有要递归的目录。你的意思是:grep -vi terry -R /tmp/log --include '*.log' | grep -i --color=always 'err'。请阅读手册页:grep(1)。
猜你喜欢
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
  • 2019-02-18
  • 2018-12-13
相关资源
最近更新 更多