如果匹配,如何用sed,awk,grep提取日志部分

时间:2016-11-11 16:12:56

标签: bash awk sed

我试图提取与特定字符串匹配的日志部分。

我的日志文件包含一系列HTTP流量(请求/响应)。例如:

[2016-11-11 06:52:07.452] [jettyserver-391] 201939 * Server has received a request on thread jettyserver-391
201939 > PUT http://localhost
201939 > Accept: application/json
201939 > Accept-Encoding: gzip
201939 > Content-Type: application/json
201939 > Host: localhost
201939 > Transfer-Encoding: chunked
{
  "att1": "WIFI",
  "att2": true,
  "att3": null,
  "country": "CANADA",
  "att5": null
}

[2016-11-11 06:52:07.555] [jettyserver-392] 201940 * Server has received a request on thread jettyserver-392
201940 > PUT http://localhost
201940 > Accept: application/json
201940 > Accept-Encoding: gzip
201940 > Content-Type: application/json
201940 > Host: localhost
201940 > Transfer-Encoding: chunked
{
  "att1": "ETHERNET",
  "att2": true,
  "att3": null,
  "country": "US",
  "att5": null
}

[2016-11-11 06:52:07.557] [jettyserver-391] 201940 * Server responded with a response on thread jettyserver-391
201939 < 200
201939 < Content-Type: application/json
{
  "id": 344134
}

[2016-11-11 06:52:07.557] [jettyserver-392] 201940 * Server responded with a response on thread jettyserver-392
201940 < 200
201940 < Content-Type: application/json
{
  "id": 344135
}

如果我搜索&#34;以太网&#34;,我期待这个输出:

[2016-11-11 06:52:07.555] [jettyserver-392] 201940 * Server has received a request on thread jettyserver-392
201940 > PUT http://localhost
201940 > Accept: application/json
201940 > Accept-Encoding: gzip
201940 > Content-Type: application/json
201940 > Host: localhost
201940 > Transfer-Encoding: chunked
{
  "att1": "ETHERNET",
  "att2": true,
  "att3": null,
  "country": "US",
  "att5": null
}

现在,我尝试了sed,我已经半成功了:

sed -n '/^\[/{x;/ETHERNET/{p;d}};/ETHERNET/H' test2

我有这个输出......

[2016-11-11 06:52:07.555] [jettyserver-392] 201940 * Server has received a request on thread jettyserver-392
  "att1": "ETHERNET",

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

如果其已知部分(5行后上下文(-A5),8行前上下文(-B8)),您可以grep使用-A和{ {1}}选项,这应该打印前面的8行和包含匹配行后的5行:

-B