Unix中grep -B / -A选项的替换/等价物是什么?

时间:2016-06-18 15:57:43

标签: bash grep posix

由于Unix没有为grep提供-A-B选项,我正在寻找在Unix中实现相同结果的方法。 目的是打印所有不以特定模式和前一行开头的行。

grep -B1 -v '^This' Filename

这将打印所有不以字符串'This'和前一行开头的行。不幸的是我的脚本需要在Unix上运行。 任何解决方法都会很棒。

1 个答案:

答案 0 :(得分:6)

您可以使用awk

awk '/pattern/{if(NR>1){print previous};print}{previous=$0}'

说明:

# If the pattern is found
/pattern/ {
    # Print the previous line. The previous line is only set if the current
    # line is not the first line.
    if (NR>1) {
        print previous
    }
    # Print the current line
    print
}
# This block will get executed on every line
{
    # Backup the current line for the case that the next line matches
    previous=$0
}
相关问题