grep invert 没有按我预期的方式工作

grep invert 没有按我预期的方式工作

我正在尝试从我的应用程序日志文件中 grep 一些文本,但我真的不明白为什么它不起作用...首先,我提取文件中可能包含我想要的内容的每个部分,然后我想排除那些包含一些我不想要的单词的部分。问题是我想删除第一个 grep 找到的整个块,而不仅仅是行。我正在尝试这样做:

grep -A 5 "header of start parts" file.log | grep -v "piece of unwanted words" -A 2 -B 3

因此,我认为使用 -A 2 和 -B 3 会删除第二个 grep 中的整个块,但事实并非如此。它仍然给我带有不需要的单词的结果...这是我的文件的模式:

Some text to ignore
Some Text to ignore
header of start parts
line to get together
line to get together
line to get together
line to get together
line to get together
Some text to ignore
header of start parts
line to get together
line with piece of unwanted words
line to get together
line to get together
line to get together
A lot of other logs and this patterns repeating

所以我的第一个 grep 会给我所有出现这种情况的结果:

header of start parts
line to get together
line to get together
line to get together
line to get together
line to get together

和这个:

header of start parts
line to get together
line with piece of unwanted words
line to get together
line to get together
line to get together

第二个 grep 我想要排除我发布的第二个块的所有内容。提前感谢您的帮助。

答案1

由于grep有助于界定上下文块(默认情况下使用字符串),您可以将--第一个的结果传递给grepawk段落模式并排除整个记录与第二个片段匹配:

$ grep -A5 "header of start parts" file.log | 
  awk -vRS='\n--\n' '!/line with piece of unwanted words/'
header of start parts
line to get together
line to get together
line to get together
line to get together
line to get together

相关内容