簡體   English   中英

如何使用AWK從Web日志中收集IP和用戶代理信息?

[英]How to gather IP and User Agent info from web log with AWK?

我有一個日志文件,包含如下文字:

66.249.74.18 - - [21/Apr/2013:05:55:33 +0000] 200 "GET /1.jpg HTTP/1.1" 7691 "-" "Googlebot-Image/1.0" "-"
220.181.108.96 - - [21/Apr/2013:05:55:33 +0000] 200 "GET /1.html HTTP/1.1" 17722 "-" "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)" "-"

我想將所有ip和用戶代理信息收集到一個文件中:

66.249.74.18 "Googlebot-Image/1.0"
220.181.108.96 "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)"

我怎么能用awk做到這一點?

我知道awk '{print $1}'可以列出所有ips和awk -F\\" '{print $6}'可以列出所有用戶代理,但我不知道如何將它們組合成輸出。

awk '{print $1,$6}' FPAT='(^| )[0-9.]+|"[^"]*"'
  • 將字段定義為
    • 從行或空間的開頭開始
    • 然后是[0-9.]+"[^"]*"
  • 然后打印字段1和6

不使用GNU擴展的可移植方法:

awk '{printf "%s ",$1;for(i=12;i<NF;i++)printf "%s ",$i;printf "\n"}' file
awk -F' - |\\"' '{print $1, $7}' temp1

輸出:

66.249.74.18 Googlebot-Image/1.0
220.181.108.96 Mozilla/5.0 (compatible;Baiduspider/2.0;+http://www.baidu.com/search/spider.html)

temp1文件:

66.249.74.18 - - [21/Apr/2013:05:55:33 +0000] 200 "GET /1.jpg HTTP/1.1" 7691 "-" "Googlebot-Image/1.0" "-"
220.181.108.96 - - [21/Apr/2013:05:55:33 +0000] 200 "GET /1.html HTTP/1.1" 17722 "-" "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)"     "-"

使用perl

perl -nle '/^((?:\d+\.?){4})(?:.+?"){4}\s+(".*?")/ && print "$1 $2"' access_log

訣竅在於計算不是雙引號+雙引號的字符 : (?:.+?"){4} 。這是正則表達式的直觀描述: https//regex101.com/r/xP0kF4/4

正則表達式比以前的答案更復雜,但我們可以輕松地解析其他屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM