grep - 之前打印行,不打印匹配 [英] grep - print line before, don't print match
本文介绍了grep - 之前打印行,不打印匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何轻松地在匹配上方打印行并跳过匹配本身?grep
-A
, -B
和 -o
opt 不解决.也许一些 awk
魔法?
How to easily print line above the match and skip the match itself? grep
-A
, -B
and -o
opt do not solve it. Maybe some awk
magic?
例如:
$ cat foo.txt
bar
foo
baz
foo
$ cat foo.txt | grep foo-SOMETHING
bar
baz
编辑
- 如果第 2 行和第 3 行有foo",则应打印第 1 行和第 2 行(虽然我在这里不是很严格)
附加功能:考虑示例:
bar
foo
baz
foo
foo
理想情况下应该返回
bar
baz
foo
推荐答案
awk '!/foo/ { line = $0 }
/foo/ { print line }' foo.txt
第一个子句将每个非 foo 行保存在一个变量中.当行匹配 foo
时,第二个子句打印最近保存的行.
The first clause saves each non-foo line in a variable. The second clause prints the most recent saved line when the line matches foo
.
这也有效(并处理连续有两行 foo
的情况):
This also works (and handles the case where you have two foo
lines in a row):
awk '/foo/ {print line}
{line = $0}' foo.txt
使用 grep
你可以:
grep -B 1 foo foo.txt | grep -vE 'foo|^--$'
第二个命令过滤掉 foo
行和匹配块之间打印的分隔符.
The second command filters out the foo
lines and the dividers that are printed between the matching blocks.
这篇关于grep - 之前打印行,不打印匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文