在没有条目时使用 awk 不工作按最后 15 分钟过滤访问日志

Filtering access logs by last 15 minutes with awk not working when there are no entries

我有一个具有以下格式的 apache 访问日志,我正在尝试使用 awk 命令过滤掉最近 15 分钟的请求。当有条目时它工作正常,但是当在过去 15 分钟内找到 none 时 returns 一切。

awk -vDate=`date -d'now-15 minute' +[%d/%b/%Y:%H:%M:%S` ' { if ( > Date) print }' 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() > before {
        print 
    }
    ' \
    ""

这样执行:

./apachelogs.sh access.log