如何控制grep命令显示在相关文本前后的行数

如何控制grep命令显示在相关文本前后的行数

June 19, 2018

在Linux/Unix系统中使用grep命令的时候,有时候我们想要把匹配文本的前后几行的信息也同时显示出来。这可以通过设置一些参数来达到目的。

grep的帮助文档中有这几个参数:

-A num, –after-context=num
Print num lines of trailing context after each match.

-B num, –before-context=num
Print num lines of leading context before each match.

-C num, –context=num Print num lines of leading and trailing context surrounding each match.

-A 表示同时输出匹配行的后面几行

grep -A 5 word /home/test/a.log

-B 表示同时输出匹配行的前面几行

grep -B 5 word /home/test/a.log

-C 表示同时输出匹配行的前面几行和后面几行

grep -C5 word /home/test/a.log
最后更新于