如何让grep打印每条匹配线下方和上方的线?

时间:2009-07-02 05:25:16

标签: linux grep

  

可能重复:
  grep a file, but show several surrounding lines?

我必须解析一个非常大的文件,我想使用命令grep(或任何其他工具)。

我想在每个日志行中搜索单词FAILED,然后打印每条匹配行上方和下方的行以及匹配行。

例如:

id : 15
Satus : SUCCESS
Message : no problem

id : 15
Satus : FAILED
Message : connection error

我需要打印:

id : 15
Satus : FAILED
Message : connection error

3 个答案:

答案 0 :(得分:639)

grep的-A 1选项会给你一行; -B 1之前会给你一行;并且-C 1结合了两者,在前后都给你一行,-1也是如此。

答案 1 :(得分:41)

使用-B,-A或-C选项

grep --help
...
-B, --before-context=NUM  print NUM lines of leading context
-A, --after-context=NUM   print NUM lines of trailing context
-C, --context=NUM         print NUM lines of output context
-NUM                      same as --context=NUM
...

答案 2 :(得分:32)

使用-A和-B开关(意思是后面的行和后面的行):

grep -A 1 -B 1 FAILED file.txt