仅当某个单词后面跟着另一个单词时才对日志进行 grep

仅当某个单词后面跟着另一个单词时才对日志进行 grep

我有一个日志文件,其中包含如下条目:

输入

php notice bob
php notice winner
php notice blah winner
php notice asfsdf test
php erro)r bob                                                                                                
php error winner
php error trash winner
php error junk test
print this line

输出

php notice winner
php notice blah winner                                                                                        
php error winner
php error trash winner
print this line

我试图匹配日志文件中的所有行,除非 - 它包含php后跟errornotice。如果它包含php后跟errornotice,那么它应该只匹配winner字符串中也有 的情况。我的 regex-foo 很弱。谢谢。

答案1

用这个:grep 'php\s\+\(error\|notice\).*winner' mylogfile

答案2

可能有办法让 grep 在一个字符串中完成这个任务,但我个人认为我会用脚本来处理这个问题,无论是在 perl 还是 bash 中。在 bash 中,它会是这样的

while read line
do
# If line contains "php error" or "php notice" and "winner", print it, else skip it
   if echo $line | grep "php error" >/dev/null  || echo $line | grep -q "php notice" >/dev/nulll; then
       if echo $line | grep "winner" > /dev/null; then
           echo $line
       fi
   else 
   # If line does not contain "php error" or "php notice", print it.
       echo $line
   fi
done

我现在没有方便的系统来测试/调试这个,所以你可能需要稍微调整一下。

相关内容