我正在寻找一个命令,可以在特定匹配后 grep 20 行或更多行。
例子:grep "09:55:21,651" mylog_file.log
2018-02-26 09:55:21,651 ERROR [WebContainer : 0] (CommonAction.java:253) - SITAConnector Error: Empty SITA Response XML
com.ac.ccaswitch.exception.SitaConnectorException: Empty SITA Response XML
at com.ac.ccaswitch.connector.sita.SITAConnector.sendToSitaQueue(SITAConnector.java:144)
at com.ac.ccaswitch.entry.CommonAction.performTask(CommonAction.java:212)
at com.ac.ccaswitch.entry.PaymentServlet.doPost(PaymentServlet.java:85)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:738)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1694)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:970)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:508)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:181)
at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:91)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:878)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1592)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:191)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:454)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:516)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:307)
at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:84)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
答案1
您可以使用 grep 的 -An 开关在匹配后获取 n 行,因此对于您的示例来说,这将是
grep -A20 "09:55:21,651" mylog_file.log
编辑:看起来您的 grep 版本不支持 -A。所以这是一个你可以使用的小脚本
#!/bin/sh
file="$1"
pattern="$2"
n="$3"
matches="$(grep -n ${pattern} ${file})"
echo "${matches}" | while read match; do
line="${match%%:*}"
sed -n "${line},$((${line} + ${n} - 1))p" < "${file}"
done
你可以这样使用它:sh script.sh mylog_file.log "09:55:21,651" 20
编辑2:当我在这里时,这是一个使用 head 和 tail 而不是 sed 的解决方案,以防万一你的 sed 也很奇怪
#!/bin/sh
file="$1"
pattern="$2"
n="$3"
matches="$(grep -n ${pattern} ${file})"
echo "${matches}" | while read match; do
line="${match%%:*}"
head "-$((${line} + ${n} - 1))" "${file}" | tail "-${n}"
done