Home > Software engineering >  conditional statement with awk
conditional statement with awk

Time:10-20

I'm new with linux

I'm trying to get logs between two dates with gawk.

this is my log

Oct 07 11:00:33 abcd
Oct 08 12:00:33 abcd
Oct 09 14:00:33 abcd
Oct 10 21:00:33 abcd

I can do it when both start and end date are sent

but I have problem when start or end date or both are not sent

and I don't know how to check it .

I've written below code but it has syntax error .

sudo gawk -v year='2022'  -v start='' -v end='2022:10:08 21:00:34' '
 BEGIN{ gsub(/[:-]/," ", start); gsub(/[:-]/," ", end) }
{ dt=year" "$1" "$2" "$3; gsub(/[:-]/," ", dt) }
if(start && end){mktime(dt)>=mktime(start) && mktime(dt)<=mktime(end)}
else if(end){mktime(dt)<=mktime(end)} 
else if(start){mktime(dt)>=mktime(start)} ' log.txt

How can I modify this code ?

CodePudding user response:

This would be easier with dateutils, e.g.:

<infile dategrep -i '%b %d %H:%M:%S' '>Oct 08 00:00:00' |
        dategrep -i '%b %d %H:%M:%S' '<Oct 09 23:59:59'

Output:

Oct 08 12:00:33 abcd
Oct 09 14:00:33 abcd

CodePudding user response:

I'd write:

gawk -v end="Oct 10 12:00:00" '
    function to_epoch(timestamp,     n, a) {
        n = split(timestamp, a, /[ :]/)
        return mktime(strftime("%Y", systime()) " " month[a[1]] " " a[2] " " a[3] " " a[4] " " a[5])
    }

    BEGIN {
        split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", m)
        for (i=1; i<=12; i  ) month[m[i]]=i

        if (start) {_start = to_epoch(start)} else {_start = 0}
        if (end)   {_end   = to_epoch(end)}   else {_end   = 2**31}
    }

    { ts = to_epoch($0) }
    _start <= ts && ts <= _end
' log.txt

You'll pass the start and/or end variables with the same datetime format as appears in the log file.

  • Related