DEV Community

Query Filter
Query Filter

Posted on

filter6

#!/bin/bash

if [ -z "$1" ] || [ -z "$2" ]; then
    echo "Usage: $0 <date_col> <days_back> [delimiter]"
    exit 1
fi

DATE_COL="$1"
DAYS="$2"
DELIM="${3:--}"

# FIXED: go BACK in time, not forward!
CUTOFF=$(date -d "$DAYS days ago" +%s)

awk -v col="$DATE_COL" -v cutoff="$CUTOFF" -F"$DELIM" '
function month2num(m) {
    return (index("JanFebMarAprMayJunJulAugSepOctNovDec", m) + 2)/3
}
{
    if (NF < col) next
    d = $col
    sub(/:[0-9]{3}/, "", d)   # properly remove milliseconds
    if (d !~ /AM|PM$/) d = d " "   # ensure space before AM/PM if missing
    match(d, /^([A-Za-z]{3})[[:space:]]+([0-9]{1,2})[[:space:]]+([0-9]{4})[[:space:]]+([0-9]{1,2}):([0-9]{2}):([0-9]{2})[[:space:]]+(AM|PM)/, a) || next
    mon = month2num(toupper(a[1]))
    ts = mktime(a[3] " " mon " " a[2] " " (a[4]+(a[7]=="PM" && a[4]<12?12:0)-(a[7]=="AM" && a[4]==12?12:0)) " " a[5] " " a[6])
    if (ts >= cutoff) print
}
'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)