如何grep某个模式上下的行

Rpj*_*Rpj 4 grep

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

Foo  line
Bar line
Baz line

....

Foo1 line
Bar line
Baz1 line

....
Run Code Online (Sandbox Code Playgroud)

fed*_*qui 12

使用grep与参数-A-B指示线的数量A压脚提升和BEFORE要打印在你的模式:

grep -A1 -B1 yourpattern file
Run Code Online (Sandbox Code Playgroud)
  • An代表n比赛后的"线".
  • Bm代表m"比赛前"的线.

如果两个数字相同,只需使用-C:

grep -C1 yourpattern file
Run Code Online (Sandbox Code Playgroud)

测试

$ cat file
Foo  line
Bar line
Baz line
hello
bye
hello
Foo1 line
Bar line
Baz1 line
Run Code Online (Sandbox Code Playgroud)

我们是grep:

$ grep -A1 -B1 Bar file
Foo  line
Bar line
Baz line
--
Foo1 line
Bar line
Baz1 line
Run Code Online (Sandbox Code Playgroud)

要摆脱组分隔符,您可以使用--no-group-separator:

$ grep --no-group-separator -A1 -B1 Bar file
Foo  line
Bar line
Baz line
Foo1 line
Bar line
Baz1 line
Run Code Online (Sandbox Code Playgroud)

来自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.
Run Code Online (Sandbox Code Playgroud)