Search code examples
bashdatedatetimelogfiles

extract last 10 minutes from logfile


Trying to find a simple way for watching for recent events (from less than 10 minutes), I've tried this:

awk "/^$(date --date="-10 min" "+%b %_d %H:%M")/{p++} p" /root/test.txt

but it doesn't work as expected...

Log files are in form :

Dec 18 09:48:54 Blah
Dec 18 09:54:47 blah bla
Dec 18 09:55:33 sds
Dec 18 09:55:38 sds
Dec 18 09:57:58 sa
Dec 18 09:58:10 And so on...

Solution

  • You can match the date range using simple string comparison, for example:

    d1=$(date --date="-10 min" "+%b %_d %H:%M")
    d2=$(date "+%b %_d %H:%M")
    while read line; do
        [[ $line > $d1 && $line < $d2 || $line =~ $d2 ]] && echo $line
    done
    

    For example if d1='Dec 18 10:19' and d2='Dec 18 10:27' then the output will be:

    Dec 18 10:19:16
    Dec 18 10:19:23
    Dec 18 10:21:03
    Dec 18 10:22:54
    Dec 18 10:27:32
    

    Or using awk if you wish:

    awk -v d1="$d1" -v d2="$d2" '$0 > d1 && $0 < d2 || $0 ~ d2'