Wolfgang
Wolfgang

Reputation: 575

search condition to find if logs are present for previous hour.

I am creating one unix script to check if logs are generated for one of our job. logs are getting save in the file with the timestamp like

2017 Apr 11 13:09:54:384 - Required information will be present here.
2017 Apr 11 13:17:31:578 - Required information will be present here.

we are stuck on the seach condition which will check if logs are present for the previous hour.

How I can write this if statement which will check this?

Upvotes: 0

Views: 39

Answers (2)

sat
sat

Reputation: 14949

With using grep & date:

grep -c "^$(date -d '-1 hour' '+%Y %b %d %H:')"

Here, date command generates timestamp that matches with log file. Then, grep for the timestamp in log file. -c prints a count of matching lines of file.

Upvotes: 2

ewcz
ewcz

Reputation: 13087

it's perhaps a bit dirty solution, but you could construct first the "prefix" for the previous hour, i.e., 2017 Apr 11 12 and then check how many lines in the log file match:

#get the prefix
prefix=$(date -d'-1 hour' +'%Y %b %d %H')

#count matching lines
cnt=$(gawk -F':' "\$1==\"$prefix\"" test.log | wc -l)
echo $cnt

Assuming that test.log contains

2017 Apr 11 12:09:54:384 - Required information will be present here.
2017 Apr 11 13:17:31:578 - Required information will be present here.

then the value of the variable cnt above will be 1 (if the date command yields 2017 Apr 11 12). So then you could branch your script on the basis of $cnt...

Upvotes: 1

Related Questions