我想搜索某个图案(比如条线),还要在图案的上方和下方(即1行)打印线条或在图案上方和下方打印2条线。
Foo line
Bar line
Baz line
....
Foo1 line
Bar line
Baz1 line
....
答案 0 :(得分:11)
使用带有grep
和-A
参数的-B
来表示您想要在模式周围打印的行A
和B
的行数a :
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.
答案 1 :(得分:2)
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