mike01010
mike01010

Reputation: 6068

using Find/Grep to search files between specific time of day

I can use the following command to search log files over the past 10 days:

find . -type f -mtime -10 |xargs grep -i -n 'exception' 2> /dev/null

But i want to further limit the search for lines in the file that are logged between 6am and 6pm. I'm wondering how i can modify the grep command to filter these if the lines look like this:

2012-09-04 03:50:41,658 [MainLogger: ] EXCEPTION  AppLog - some exception 1
2012-09-04 10:01:32,902 [MainLogger: ] EXCEPTION  AppLog - some exception 2
2012-09-04 15:39:51,901 [MainLogger: ] EXCEPTION  AppLog - some exception 3
2012-09-04 18:12:51,901 [MainLogger: ] EXCEPTION  AppLog - some exception 4

In the above case on lines 2 and 3 should be returned since they are between 6am and 6pm.

any help would be appreciated

Upvotes: 2

Views: 5124

Answers (3)

tripleee
tripleee

Reputation: 189628

In any language with a proper datetime library, converting all dates to a canonical representation makes the problem trivial. The default canonicalization is to convert to seconds since midnight, Jan 1, 1970. Then just see if the canonical number of the input line is bigger than the start time and smaller than the end time.

Upvotes: 0

rks
rks

Reputation: 920

One easy ugly way to do it could be adding a lot of greps, like this :

find . -type f -mtime -10 |xargs grep -i -n 'exception' | grep -v " 00" | grep -v " 01" | ... | grep -v " 18" | grep -v " 19" ... 2> /dev/null

Or more concisely :

find . -type f -mtime -10 |xargs grep -i -n 'exception' | grep -v -e " \(0[012345]\|18\|19\|2[0123]\)" 2> /dev/null

Upvotes: 2

choroba
choroba

Reputation: 241968

You can hack it like this:

grep ' 0[6789]:\| 1[01234567]\| 18:00:00,000'

But if you will need some more time handling, I recommend switching to a more powerful language (e.g. Perl and DateTime).

Upvotes: 1

Related Questions