How to grep for lines above and below a certain pattern
我想搜索一个特定的图案(比如条线),还要在图案上方和下方(即1行)打印线条,或者在图案上方和下方打印2条线条。
1 2 3 4 5 6 7 8 9 10 11 | Foo line Bar line Baz line .... Foo1 line Bar line Baz1 line .... |
使用带参数
1 | grep -A1 -B1 yourpattern file |
-
An 代表"匹配后"的n 行。 -
Bm 代表"匹配前"的m 行。
如果两个数字相同,只需使用
1 | grep -C1 yourpattern file |
测试
1 2 3 4 5 6 7 8 9 10 | $ cat file Foo line Bar line Baz line hello bye hello Foo1 line Bar line Baz1 line |
我们
1 2 3 4 5 6 7 8 | $ grep -A1 -B1 Bar file Foo line Bar line Baz line -- Foo1 line Bar line Baz1 line |
要删除组分隔符,可以使用
1 2 3 4 5 6 7 | $ grep --no-group-separator -A1 -B1 Bar file Foo line Bar line Baz line Foo1 line Bar line Baz1 line |
来自
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | -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. |
1 | 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 |
注意,这也会找到一个命中。
或者用
1 | grep -A2 -B1"Bar" file |