Linux

在 grep -B 之後合併行

  • April 7, 2018

我正在嘗試從日誌文件中解析一些數據。前提是我需要一個比我想要的模式高 2 行的日期。

我可以用 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"

實現這一目標的最佳方法是什麼?

**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"

引用自:https://unix.stackexchange.com/questions/436232