我想搜索每一行的单词FAILED,然后打印每一行的上面和下面的匹配,以及匹配的行。


输入:

id : 15
Status : SUCCESS
Message : no problem

id : 15
Status : FAILED
Message : connection error

grep 'FAILED'的期望输出:

id : 15
Status : FAILED
Message : connection error

使用-A和-B开关(前后平均行):

grep -A 1 -B 1 FAILED file.txt

使用-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
...

grep的-A 1选项将在;- b1会给你前面一行;-1将两者结合在一起得到前后各一行,-1也是一样。