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

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

我想解析一些输出,因此我排除包含fooor的所有行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

我想要输出:

1 some line
6 another line

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

答案1

也许awk

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

答案2

尝试这个 :

grep -v "$(grep -E -B1 "foo|bar" InputFile)" InputFile

答案3

这是本质上相同的事情的更详细版本@1_CR贴在上面,@ash 显示在帕斯特宾,希望使用更易读的语法:

awk '{
        lastLine = currentLine;
        currentLine = $0;
    }

    /foo|bar/ \
    {
        getline currentLine
        next
    }

    NR > 1 \
    {
        print lastLine;
    }

    END \
    {
        if ( currentLine !~ /foo|bar/ )
            print currentLine;
    }
    ' InputFile

相关内容