Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk for date ranges date format like mm/dd/yyyy hh:mm:ss

Tags:

awk

I have my log file like this i am trying retrive date range

"07/10/2013 01:31:54","SNMP" 

"07/10/2013 01:31:54","SNMP" 
.... ... .. 
"07/10/2013 03:03:54","SNMP"

I am using fallowing awk command, it gives all the rows, i tried different combination no use, is there standard data format need to use in awk?

awk -F, '"07/10/2013 01:35:40" > $1&&$1 <= "07/10/2013 01:50:03"' Mylog.log | wc -l
like image 886
Mallikarjunarao Kosuri Avatar asked Jan 21 '26 13:01

Mallikarjunarao Kosuri


1 Answers

You have two problems: CSV parsing and date comparison.

The first one you can solve using match(), or a CSV parsing function.

The second one you can solve by either using a proper date format like ISO-8601, a happy side-effect being that dates (ex timezone/DST changes) can be compared lexically. If you are really using gawk instead of plain awk or nawk you can use the built-in date function mktime() to parse timestamps and return an epoch-second ordinal which allows dates to be compared numerically. awk has no native date/time types, and no standard data/time libraries, so lexical or numeric comparisons are the most straightforward option here.

A final option with gawk is a nasty hack:

/^"07.10.2013 01:35:40"/,/^"07.10.2013 01:50:03"/ {
    # your code here
}

This uses a range expression to limit the scope of matching to between certain lines. This should work for your file format as long as the times are monotonic increasing – this is not true for Apache logs (since they are logged in order of completion, but by default contain the original request time stamp, and are not guaranteed to be monotonic increasing).

like image 142
mr.spuratic Avatar answered Jan 25 '26 16:01

mr.spuratic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!