grep的 - 前打印线,不打印匹配 [英] grep - print line before, don't print match
问题描述
如何轻松打印线比赛上面,并跳过比赛本身? 的grep
-A
, -B
和 -o
选择不解决它。也许有些 AWK
魔法?
例如:
$猫foo.txt的
酒吧
富
巴兹
富$猫foo.txt的| grep的富出头
酒吧
巴兹
修改
- 在情况下,当线2和3的富,那么1号线和2应打印(虽然我不是很严格这里)
附加功能:考虑例如:
酒吧
富
巴兹
富
富
这应该理想返回
酒吧
巴兹
富
的awk'!/富/ {线= $ 0}
/富/ {打印线}'foo.txt的
第一条保存在一个变量中的每个非富线。第二条打印最近保存线时行匹配富
。
这也可以(和处理,你必须在连续两个富
线的情况下):
的awk'/富/ {打印线}
{线= $ 0}'foo.txt的
使用的grep
你可以这样做:
的grep -B 1富foo.txt的| grep的-vE'富| ^ - $'
第二个命令过滤出富
行和打印匹配块之间的分隔。
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?
for example:
$ cat foo.txt
bar
foo
baz
foo
$ cat foo.txt | grep foo-SOMETHING
bar
baz
Edit
- in case when line 2 and 3 has "foo", then line 1 and 2 should be printed (although I am not very strict here)
Additional feature: consider the example:
bar
foo
baz
foo
foo
This should ideally return
bar
baz
foo
awk '!/foo/ { line = $0 }
/foo/ { print line }' foo.txt
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
.
This also works (and handles the case where you have two foo
lines in a row):
awk '/foo/ {print line}
{line = $0}' foo.txt
With grep
you can do:
grep -B 1 foo foo.txt | grep -vE 'foo|^--$'
The second command filters out the foo
lines and the dividers that are printed between the matching blocks.
这篇关于grep的 - 前打印线,不打印匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!