grep -B 之后合并行

grep -B 之后合并行

我正在尝试解析日志文件中的一些数据。前提是我需要一个比我想要的模式高出两行的日期。

我可以用 grep 达到这个目的:

> grep -B2 "rc_transaction result=" xml.log

每个模式查找的输出为 3 行:

03 Apr 12:48:42.503 [6086-16592] DEBUG c.q.q.d.server.XmlServlet - <?xml version="1.0"?>
<stream id="18561">
<rc_transaction result="ok" vst_time="2018-04-03 10:48:42.431" transaction_time="2018-04-03 10:48:42.497" sequence_number="117749" code="0">
--
03 Apr 12:49:21.936 [6086-16592] DEBUG c.q.q.d.server.XmlServlet - <?xml version="1.0"?>
<stream id="18566">
<rc_transaction result="ok" vst_time="2018-04-03 10:49:21.839" transaction_time="2018-04-03 10:49:21.930" sequence_number="117750" code="0">
--
03 Apr 12:49:39.654 [6086-16592] DEBUG c.q.q.d.server.XmlServlet - <?xml version="1.0"?>
<stream id="18569">
<rc_transaction result="ok" vst_time="2018-04-03 10:49:39.582" transaction_time="2018-04-03 10:49:39.648" sequence_number="117751" code="0">

现在,我需要解析这个结果并获取第一行的日期和第三行的一些属性,如下所示:

03 Apr 12:48:42.503 result="ok" sequence_number="117749"
03 Apr 12:49:21.936 result="ok" sequence_number="117750"
03 Apr 12:49:39.654 result="ok" sequence_number="117751"

实现这一目标的最佳方法是什么?

答案1

Awk解决方案:

awk '/<\?xml/{ date=$1 OFS $2 OFS $3 }/rc_transaction result=/{ print date, $2, $7 }' xml.log

输出:

03 Apr 12:48:42.503 result="ok" sequence_number="117749"
03 Apr 12:49:21.936 result="ok" sequence_number="117750"
03 Apr 12:49:39.654 result="ok" sequence_number="117751"

相关内容