DEV Community

Query Filter
Query Filter

Posted on

fil9

#!/bin/bash
# filter_lastNdays.sh  –  works with your exact format as of Nov 2025

[[ -z "$1" || -z "$2" ]] && {
    echo "Usage: $0 <column> <days_back> [delimiter]"
    echo "Example: cat Zxtra.dat | $0 4 60"
    exit 1
}

COL="$1"
DAYS="$2"
DELIM="${3:-~}"           # your files use ~ as delimiter

# Correct cutoff: N days ago (this was the #1 bug before)
CUTOFF=$(date -d "$DAYS days ago" +%s)

awk -v col="$COL" -v cutoff="$CUTOFF" -F"$DELIM" '
function month2num(m) {
    return (index("JanFebMarAprMayJunJulAugSepOctNovDec", m) + 2) / 3
}
{
    if (NF < col) next                                 # skip malformed lines

    d = $col

    # Remove milliseconds (:123) → leave space + AM/PM intact
    sub(/:[0-9]{3}/, "", d)

    # Regex that exactly matches your real data:
    # Oct 10 2025  9:03:05PM   or   Oct 11 2025  2:51:22PM
    if (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)) {
        mon  = month2num(a[1])
        mday = a[2] + 0
        year = a[3] + 0
        hour = a[4] + 0
        min  = a[5] + 0
        sec  = a[6] + 0
        ap   = a[7]

        if (ap == "PM" && hour < 12) hour += 12
        if (ap == "AM" && hour == 12) hour = 0

        ts = mktime(year " " mon " " mday " " hour " " min " " sec)
        if (ts >= cutoff) print $0
    }
    # any line that doesn’t match the date pattern is silently skipped
}'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)