![如何 grep 2 或 3 行,其中一行包含我想要的文本,其他行位于其下方?](https://linux22.com/image/957260/%E5%A6%82%E4%BD%95%20grep%202%20%E6%88%96%203%20%E8%A1%8C%EF%BC%8C%E5%85%B6%E4%B8%AD%E4%B8%80%E8%A1%8C%E5%8C%85%E5%90%AB%E6%88%91%E6%83%B3%E8%A6%81%E7%9A%84%E6%96%87%E6%9C%AC%EF%BC%8C%E5%85%B6%E4%BB%96%E8%A1%8C%E4%BD%8D%E4%BA%8E%E5%85%B6%E4%B8%8B%E6%96%B9%EF%BC%9F.png)
这是错误日志的快照:
06:16:29,933 ERROR EmailRMManager$:45 - Exception In get Message
com.rabbitmq.client.AlreadyClosedException: clean connection shutdown; reason: Attempt to use closed channel
at com.rabbitmq.client.impl.AMQChannel.ensureIsOpen(AMQChannel.java:195)
at com.rabbitmq.client.impl.AMQChannel.rpc(AMQChannel.java:222)
at com.rabbitmq.client.impl.AMQChannel.rpc(AMQChannel.java:208)
at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:139)
at com.rabbitmq.client.impl.ChannelN.basicGet(ChannelN.java:645)
我执行以下命令:
cat foo.log | grep ERROR
得到如下 OP:
06:16:29,933 ERROR EmailRMManager$:45 - Exception In get Message
我应该执行什么命令才能获得输出
06:16:29,933 ERROR EmailRMManager$:45 - Exception In get Message
com.rabbitmq.client.AlreadyClosedException: clean connection shutdown; reason: Attempt to use closed channel
即,也 grep 模式后的行?
答案1
只需执行以下操作:
grep -A1 ERROR
告诉-A1
grep 在匹配后包含 1 行。-B
包括匹配前的行,以防您也需要。
答案2
更便携的方式是使用 awk
awk '/ERROR/{n=NR+1} n>=NR' foo.log
或者也许您想要所有以下的缩进行?
awk '/^[^[:blank:]]/{p=0} /ERROR/{p=1} p' foo.log
答案3
我找到了这个解决方案:
cat apache.error.log | grep -Pzo '^.*?Exception In get Message.*?\ncom\.rabbitmq.*?(\n(?=\s).*?)*$'
其中的(\n(?=\s).*?)*
意思是:
\n
查找下一行(?=\s)
从空格字符开始的位置.*?
直到行尾(...)*
多次查找此类行
PS.\ncom\.rabbitmq.*?
如果第二行以空格开头,则可能会破坏此模式\s
答案4
对于这个简单的任务,一个简单的方法是:
grep -A num
Print num lines of trailing context after each match. See also the -B and -C options.
grep -B num
Print num lines of leading context before each match. See also the -A and -C options.
grep -C num
Print num lines of leading and trailing context surrounding each match.
The default is 2 and is equivalent to -A 2 -B 2.
注意:选项和其参数之间不能有空格。