9

我想搜索某种模式(比如条形线),但也打印模式上方和下方的线(即 1 条线)或模式上方和下方的 2 条线。

Foo  line
Bar line
Baz line

....

Foo1 line
Bar line
Baz1 line

....
4

2 回答 2

18

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.
于 2013-10-11T08:21:06.867 回答
3

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
于 2013-10-11T08:28:47.500 回答