我想搜索某种模式(比如条形线),但也打印模式上方和下方的线(即 1 条线)或模式上方和下方的 2 条线。
Foo line
Bar line
Baz line
....
Foo1 line
Bar line
Baz1 line
....
我想搜索某种模式(比如条形线),但也打印模式上方和下方的线(即 1 条线)或模式上方和下方的 2 条线。
Foo line
Bar line
Baz line
....
Foo1 line
Bar line
Baz1 line
....
grep
与参数一起使用-A
并-B
指示要在图案周围打印的A
前后行数:B
grep -A1 -B1 yourpattern file
An
代表n
比赛“之后”的行。Bm
代表m
比赛“之前”的行。如果两个数字相同,只需使用-C
:
grep -C1 yourpattern file
$ cat file
Foo line
Bar line
Baz line
hello
bye
hello
Foo1 line
Bar line
Baz1 line
让我们grep
:
$ grep -A1 -B1 Bar file
Foo line
Bar line
Baz line
--
Foo1 line
Bar line
Baz1 line
要摆脱组分隔符,您可以使用--no-group-separator
:
$ grep --no-group-separator -A1 -B1 Bar file
Foo line
Bar line
Baz line
Foo1 line
Bar line
Baz1 line
来自man grep
:
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
Places a line containing a group separator (--) between
contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines.
Places a line containing a group separator (--) between
contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.
-C NUM, -NUM, --context=NUM
Print NUM lines of output context. Places a line containing a
group separator (--) between contiguous groups of matches. With
the -o or --only-matching option, this has no effect and a
warning is given.
grep
是你的工具,但它可以用awk
awk '{a[NR]=$0} $0~s {f=NR} END {for (i=f-B;i<=f+A;i++) print a[i]}' B=1 A=2 s="Bar" file
注意,这也会找到一击。
或与grep
grep -A2 -B1 "Bar" file