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

ins*_*246 0 bash grep posix

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

grep -B1 -v '^This' Filename

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

hek*_*mgl 6

你可以使用awk:

awk '/pattern/{if(NR>1){print previous};print}{previous=$0}'
Run Code Online (Sandbox Code Playgroud)

说明:

# 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
}
Run Code Online (Sandbox Code Playgroud)