如何grep某个模式上下的行

时间:2013-10-11 08:20:44

标签: grep

我想搜索某个图案(比如条线),还要在图案的上方和下方(即1行)打印线条或在图案上方和下方打印2条线。

Foo  line
Bar line
Baz line

....

Foo1 line
Bar line
Baz1 line

....

2 个答案:

答案 0 :(得分:11)

使用带有grep-A参数的-B来表示您想要在模式周围打印的行AB的行数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