awk date math

Just a reference post for how to determine the number of seconds between two date strings in awk. If you have a normally formatted date string in Linux, such as “Sun Mar 19 00:50:33 EDT 2017”, you can convert this to a time object with the following…

bash-4.1$ grep 2017$ list2.out | awk 'BEGIN{split("Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec",l,"|")} {for (i in l) {if ($2 == l[i]) {month=i}};split($4,t,":");t1=mktime($6" "month" "$3" "t[1]" "t[2]" "t[3]);if (last > 0 && t1-last > 35) {print $0,t1-last};last=t1}'
Sat Mar 18 17:14:18 EDT 2017 96
Sun Mar 19 00:50:33 EDT 2017 95

The mktime() command expects a date formatted as “year month day hour minute second”. If you can parse that out of string, you can convert it to a date object and perform math operations on it.

What is above prints only those lines that have a timestamp greater than 35 seconds after the previous sample. It also prints the difference in seconds between the two samples.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.