regex - grep 前一行仅针对一种特定模式

标签 regex linux grep

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

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/

相关文章:

linux - 如何使用 Grep 命令查找文本文件中的特定值

javascript - 交叉文本以找到常用词

java - 使用扫描仪的分隔符功能来查找 "abc-def"

javascript - 如何像 mysql 一样从 jQuery 中的 json 或数组数据搜索名称

linux - 使用 grep 搜索以字母 "s"开头的单词

regex - 使用 grep 命名捕获组

java - 用户将输入一些过滤条件——如何将其转换为 String.match 的正则表达式

linux - 如何在 Linux 中以连续模式插入字符串

c - 如何在符号表中添加共享库版本信息

C Shell 执行命令