按最后15分钟筛选访问日志,当没有条目时,awk不起作用



我有一个格式如下的apache访问日志,我正试图使用awk命令在最后15分钟内过滤掉请求。当有条目时,它可以正常工作,但当在最后15分钟内没有找到条目时,会返回所有内容。

awk -vDate=`date -d'now-15 minute' +[%d/%b/%Y:%H:%M:%S` ' { if ($4 > Date) print $9}' access.log

访问日志格式

10.185.248.71 - - [09/Jan/2015:19:12:06 +0000] 808840 "GET /inventoryService/inventory/purchaseItem?userId=20253471&itemId=23434300 HTTP/1.1" 500 17 "-" "Apache-HttpClient/4.2.6 (java 1.5)"

不可能直接在bash或awk中比较日期。。。但你可以比较转换成整数的日期。。。

#! /bin/bash
BEFORE=$(date -d 'now-15 minute' +"%Y%m%d%H%M%S")
awk 
-v before="${BEFORE}" 
'
function toComparableDate (date) {
# 000000000111111111122
# 123456789012345678901
# [09/Jan/2015:19:12:06
return substr(date,9,4) hMonth[substr(date,5,3)] substr(date,2,2) substr(date,14,2) substr(date,17,2) substr(date,20,2)
}
BEGIN {
hMonth["Jan"] = "01"
hMonth["Feb"] = "02"
hMonth["Mar"] = "03"
hMonth["Apr"] = "04"
hMonth["May"] = "05"
hMonth["Jun"] = "06"
hMonth["Jul"] = "07"
hMonth["Aug"] = "08"
hMonth["Oct"] = "09"
hMonth["Sep"] = "10"
hMonth["Nov"] = "11"
hMonth["Dec"] = "12"
}
toComparableDate($4) > before {
print $8
}
' 
"$1"

执行方式:

./apachelogs.sh access.log

最新更新