我有一个简单的grep命令,它返回与文件匹配的行.这是问题所在:有时,当一行匹配时,我想在它之前包含该行.我想要的是找到匹配模式的所有行的方法,然后使用不同的模式来查看每个结果之前的行是否匹配.
假设我想让所有包含'bar'的行,以及每行包含'foo'之前的行.给出这样的输入:
Spam spam eggs eggs
Let's all go to the bar.
Blah Blah Blah foo.
Meh.
foo foo foo
Yippie, a bar.
我想要一个像这样的结果:
Let's all go to the bar
foo foo foo
Yippie, a bar.
您可以使用该-B选项在匹配之前包含上下文行(还-A包括上面的上下文行,以及-C包括上下文之前和之后的上下文行).然后,您可以将结果传递给另一个grep:
# Get all lines matching 'bar' and include one line of context before each match
# Then, keep only lines matching 'bar' or 'foo'
grep bar -B1 the-file | grep 'bar\|foo'
Run Code Online (Sandbox Code Playgroud)