您的“--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
希望这一切都有意义。