Linux grep 命令查看符合条件文本的相近几行

时间:2021-09-07 22:26:31

查日志时,grep 到自己想要的行之后,还想看下符合条件的附近日志记录

man grep 发现果然已经有这个参数

Context Line Control
     -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 -A 5 'parttern' inputfile //打印匹配行的后5行
 grep -B 5 'parttern' inputfile //打印匹配行的前5行
 grep -C 5 'parttern' inputfile //打印匹配行的前后5行