如何grep在特定模式上方和下方的线条 [英] How to grep for lines above and below a certain pattern

查看:11
本文介绍了如何grep在特定模式上方和下方的线条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to search for a certain pattern (say Bar line) but also print lines above and below (i.e 1 line) the pattern or 2 lines above and below the pattern.

Foo  line
Bar line
Baz line

....

Foo1 line
Bar line
Baz1 line

....

推荐答案

使用 grep 和参数 -A-B 来表示Aafter 和 B 之前要在图案周围打印的行数 a:

Use grep with the parameters -A and -B to indicate the number a of lines After and Before you want to print around your pattern:

grep -A1 -B1 yourpattern file

  • An 代表匹配之后"的 n 行.
  • Bm 代表匹配之前"的 m 行.
    • An stands for n lines "after" the match.
    • Bm stands for m lines "before" the match.
    • 如果两个数字相同,就用-C:

      If both numbers are the same, just use -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:

      To get rid of the group separator, you can use --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在特定模式上方和下方的线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆