Linux 如何让 grep 打印每个匹配行下方和上方的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1072643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:28:54  来源:igfitidea点击:

How can I make grep print the lines below and above each matching line?

linuxgrep

提问by poiuytrez

I have to parse a very large file and I want to use the command grep (or any other tool).

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

I want to search each log line for the word FAILED, then print the line above and below each matching line, as well as the matching line.

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

For example:

例如:

id : 15
Satus : SUCCESS
Message : no problem


id : 15
Satus : FAILED
Message : connection error


And I need to print:

我需要打印:

id : 15
Satus : FAILED
Message : connection error

采纳答案by pgs

grep's -A 1option will give you one line after; -B 1will give you one line before; and -C 1combines both to give you one line both before and after, -1does the same.

grep 的-A 1选项后会给你一行;-B 1之前会给你一行;并-C 1结合两者在前后给你一行,-1做同样的事情。

回答by Milan Babu?kov

Use -A and -B switches (mean lines-after and lines-before):

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

grep -A 1 -B 1 FAILED file.txt

回答by tefozi

Use -B, -A or -C option

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