0

How can I count the number of lines that begin with the date and time stamp that matches one hour or less from now?

The file in this location /home/liamcomfort/my.log.

An example of the log's format is:

Nov 10 04:03:00 Friendly. Wholesale sweaters, no problems, sometimes overnight, inexpensive than large element. 
Nov 10 04:03:07 Now want to grab the spotlight form the official website. 
Nov 10 04:04:01 No matter who, overall planning, implementation than electric. I will be traveling to Japan tomorrow, at best. 
Nov 10 04:04:01 Get's not, the element of which that can be used, unless the slough, the bow to the policies, comprehensive package
2
  • 1
    depends on how your log looks like...do you have a short example ?
    – thom
    Nov 15, 2013 at 19:51
  • Nov 10 04:03:00 Friendly. Wholesale sweaters, no problems, sometimes overnight, inexpensive than large element. Nov 10 04:03:07 Now want to grab the spotlight form the official website. Nov 10 04:04:01 No matter who, overall planning, implementation than electric. I will be traveling to Japan tomorrow, at best. Nov 10 04:04:01 Get's not, the element of which that can be used, unless the slough, the bow to the policies, comprehensive package Nov 16, 2013 at 20:34

2 Answers 2

1
now=$( date +%s )
one_hour_ago=$( date -d "now - 1 hour" +%s )
count=0
while read -ra words; do
    timestamp=$( date -d "${words[@]:0:3}" +%s )
    if (( $one_hour_ago <= $timestamp && $timestamp <= $now )); then
        (( count ++ ))
    fi
done < filename
echo $count
3
  • 1
    words=( $line ) looks rather dangerous if, e.g., there's a glob character in the line. Moreover it seems rather useless, as read -r -a words will do the job! Nov 16, 2013 at 22:05
  • Nice one with the "now - 1 hour", i didn't even know that that was possible.
    – thom
    Nov 16, 2013 at 22:53
  • @gniourf_gniourf, I originally had a echo "$line" that I removed. I didn't want to lose the original whitespace. But your suggestion is well taken. Nov 17, 2013 at 0:11
1
while read M D T R; do [[ $(( $( date +"%s" ) - $( date -d "$M $D $T" +"%s" ) )) -lt 3600 ]] && (( ++C )); done; echo $C

Nice oneliner (sorry, couldn't resist) which works but very very ugly...
The following code, however, is how it can be done in a elegant way:

#!/bin/bash

#read the current date/time in unixtime format
NOW=$( date +"%s" )

while read MONTH DAY TIME REST
do
    #change the read date/time to unixtime
    THEN=$( date -d "$MONTH $DAY $TIME" +"%s" )

    #if the difference is less than 1 hour (=3600 seconds), increase the count
    (( ( NOW - THEN ) < 3600 )) && (( ++COUNT ))

done <"/home/liamcomfort/my.log"

echo "$COUNT"
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .