给出一个示例日志文件,例如:
interesting stuff
App: 123 blob
some text
other text
ERROR could not find file XYZ
other really cool stuff
App: 123 blob
some text
other text
ERROR stdout blocked
我想用 'ERROR' 和 'App:' 加上 'App:' 之前的行来 grep 行。 使用多个搜索模式和 -B 1 我得到匹配行以及之前的相应行:
grep -B 1 -e '^App:.*' -e '.*ERROR.*'
interesting stuff
App: 123 blob
--
other text
ERROR could not find file XYZ
other really cool stuff
App: 123 blob
--
other text
ERROR stdout blocked
(我也不知道“--”来自哪里) 但我想要的输出是:
interesting stuff
App: 123 blob
ERROR could not find file XYZ
other really cool stuff
App: 123 blob
ERROR stdout blocked
非常感谢。
最佳答案
grep
的 -B 1
选项将应用于所有表达式。在这种情况下,您可以使用 awk
:
$ awk '/App/ {print line;print} {line=$0} /ERROR/' file
interesting stuff
App: 123 blob
ERROR could not find file XYZ
other really cool stuff
App: 123 blob
ERROR stdout blocked
$
关于regex - grep 前一行仅针对一种特定模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48346772/