user2961454
user2961454

Reputation: 353

Getting difference in date in custom logger in linux

I am trying to find occurrence of string in last 5 minutes in log file using awk. Command I am trying is

awk -v d1="$(date --date="-5 min" "+%b %_d %H:%M")" -v d2="$(date "+%b %_d %H:%M")" '$0 > d1 && $0 < d2 || $0 ~ d2' /tmp/CustomService.log | grep -ci "IAM-548792" 

But this is not returing the output.

Content in log file looks like this

2016-11-07 16:08:05 DEBUG Service - Request: Started
2016-11-07 16:08:05 DEBUG Service - ##########
2016-11-07 16:08:05 DEBUG Service - Response: Completed at Mon 2016.11.07 at 04:08:05 PM EST
2016-11-07 16:08:05 DEBUG Service - IAM-548792. Internal Error

I think issue is my log has different timestamp compared to default date command linux is using. Is this causing issue?

I am getting started with awk commands. Appreciate your help.

Upvotes: 0

Views: 106

Answers (3)

Jay Rajput
Jay Rajput

Reputation: 1898

awk solution:

awk  'BEGIN { t = systime() - 300;}  # set t to 5 minutes less than now
     {gsub("-", " ", $1);            # remove - from $1 to get YYYY MM DD
      gsub(":", " ", $2);            # remove : from $2 to get HH   MM SS
      d = $1" "$2 }                  # datespec format YYYY MM DD HH MM SS
      mktime(d) > t '                # convert datespec to seconds, compare and print

One liner:

awk  -v secs=300 'BEGIN { t = systime() - secs} {gsub("-", " ", $1); gsub(":", " ", $2); d = $1" "$2 } mktime(d) > t '

See awk documentation

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246942

I would write:

read date time < <(date -d "5 mins ago" "+%F %T")
awk -v d="$date" -v t="$time" '$1 == d && $2 >= t' file

Upvotes: 0

usha
usha

Reputation: 29349

you have to change your date format

This is what you have

[user@user ~]$ date "+%b %_d %H:%M"
Nov  7 16:30

This is what you need

[user@user ~]$ date "+%F %H:%M:%S"
2016-11-07 16:32:05

Upvotes: 1

Related Questions