grep 在每次命中之前过滤所有行加一

rub*_*o77 3 grep bash filter

我想解析一些输出,所以我排除了所有包含foo或 的行bar,以及这些行之前的所有行。例如:

echo "
1 some line
2 line to exclude because the next line has one of the terms
3 line with foo
4 line to exclude because the next line has one of the terms too
5 line with bar
6 another line
">InputFile
Run Code Online (Sandbox Code Playgroud)

我想要输出:

1 some line
6 another line
Run Code Online (Sandbox Code Playgroud)

我试过cat InputFile|grep -v "foo"|grep -v "bar",但它不排除第 2 行和第 4 行,并且-B1之前的行的选项也不起作用。

iru*_*var 5

也许awk

awk 'BEGIN{a = "foo"}; a !~ /foo|bar/ && $0 !~ /foo|bar/{print a};
{a = $0};END{if(a !~ /foo|bar/){print a}}' InputFile
Run Code Online (Sandbox Code Playgroud)

  • @ash - 1_CR 拒绝了您尝试使其更具可读性的尝试。作为妥协,我创建了您编辑的粘贴箱,我同意这很重要,因为对新手`awk`er 的回答可能难以消化。http://pastebin.com/HmYbHJh7 (2认同)