grep前面的一行只针对一个特定的模式

时间:2022-01-14 08:54:00

given an example log file like:

给出一个示例日志文件,如:

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

I want to grep the line with 'ERROR' and 'App:' plus the line before 'App:'. With multiple search-patterns and -B 1 i get the matching lines plus the respective line before:

我想用‘ERROR’和‘App:’加上‘App:’之前的那行。通过多种搜索模式和- b1,我得到了匹配行加上之前的相应行:

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

(i also don't know where the '--' are coming from) but my desired output is:

(我也不知道“—”从何而来)但我想要的输出是:

interesting stuff
App: 123 blob
ERROR could not find file XYZ
other really cool stuff
App: 123 blob
ERROR stdout blocked

Thank you very much.

非常感谢。

1 个解决方案

#1


3  

grep's -B 1 option would apply to all expressions. You can use awk in this case:

grep的- b1选项将适用于所有表达式。在这种情况下,你可以使用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
$

#1


3  

grep's -B 1 option would apply to all expressions. You can use awk in this case:

grep的- b1选项将适用于所有表达式。在这种情况下,你可以使用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
$