grepとawkを使用して、ログファイルから特定の行を抽出します。

grepとawkを使用して、ログファイルから特定の行を抽出します。

特定のURLステータスが「200 OK」で応答するかどうかを示す巨大なログファイル(2000万行)があります。

添付ファイル名とともにステータスが「200 OK」のすべてのURLを抽出したいと思います。

入力例:

Spider mode enabled. Check if remote file exists.
--2019-02-06 07:38:43--  https://www.example/download/123456789
Reusing existing connection to website.
HTTP request sent, awaiting response... 
  HTTP/1.1 200 OK
  Content-Type: application/zip
  Connection: keep-alive
  Status: 200 OK
  Content-Disposition: attachment; filename="myfile123.zip"
  Last-Modified: 2019-02-06 01:38:44 +0100
  Access-Control-Allow-Origin: *
  Cache-Control: private
  X-Runtime: 0.312890
  X-Frame-Options: SAMEORIGIN
  Access-Control-Request-Method: GET,OPTIONS
  X-Request-Id: 99920e01-d308-40ba-9461-74405e7df4b3
  Date: Wed, 06 Feb 2019 00:38:44 GMT 
  X-Powered-By: Phusion Passenger 5.1.11
  Server: nginx + Phusion Passenger 5.1.11
  X-Powered-By: cloud66
Length: unspecified [application/zip]
Last-modified header invalid -- time-stamp ignored.
Remote file exists.

Spider mode enabled. Check if remote file exists.
--2019-02-06 07:38:43--  https://www.example/download/234567890
Reusing existing connection to website.
HTTP request sent, awaiting response... 
  HTTP/1.1 404 Not Found
  Content-Type: text/html; charset=utf-8
  Connection: keep-alive
  Status: 404 Not Found
  Cache-Control: no-cache
  Access-Control-Allow-Origin: *
  X-Runtime: 0.020718
  X-Frame-Options: SAMEORIGIN
  Access-Control-Request-Method: GET,OPTIONS
  X-Request-Id: bc20626b-095f-4b28-8322-ad3f294e4ee2
  Date: Wed, 06 Feb 2019 00:37:42 GMT
  X-Powered-By: Phusion Passenger 5.1.11
  Server: nginx + Phusion Passenger 5.1.11
Remote file does not exist -- broken link!!!

希望の出力:

https://www.example/download/123456789 myfile123.zip

私はついにこれの論理を理解したいと思います。

私がこうすれば:

awk '/: 200 OK/{print $0}' file.log

コンテキストはあるがコンテキストを持たないすべての行を取得しますStatus: 200 OK

私がこうすれば:

grep -C4 "1 200 OK" file.log

文脈を理解していますが、「ノイズ」があります。 1行でのみ関連情報を取得できるように、出力を並べ替えたいと思います。

ベストアンサー1

awk次のように使用する必要があります。まずURLを変数に保存し、次の行からファイル名を取得したらその行に保存しますStatus。キャプチャされたグループを配列に保存するには、関数に3番目のパラメータが必要なので、GNUOKで動作する必要があります。awkmatch()

awk '/^--/{ url = $NF } 
    /^[[:space:]]+Status/ && $NF == "OK" { getline nextline; match(nextline, /filename="(.+)"/,arr); print url, arr[1] }' file

おすすめ記事