如何在特定模式之上和之下的线条进行grep

我想搜索特定图案(比如小节线),而且打印的上方和下方(即1线)的图案或2行上方和下方的图案线条。

Foo  line
Bar line
Baz line

....

Foo1 line
Bar line
Baz1 line

....

使用带参数-A-B grep指示要在您的模式周围打印的线A fter和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.
    

    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
    
    链接地址: http://www.djcxy.com/p/19633.html

    上一篇: How to grep for lines above and below a certain pattern

    下一篇: Advanced grep unix