1

I need to display lines with Error occurred in last 10 minutes of a log file.

Aug 26 10:50:42 Normal line.
Aug 26 10:51:23 Normal line.
Aug 26 10:55:33 Error line.
Aug 26 10:56:45 Normal line.
Aug 26 10:58:12 Error line.
Aug 26 11:02:31 Normal line.
Aug 26 11:03:32 Normal line.
Aug 26 11:04:11 Normal line.

Suppose above sample of log file. I want to display only following two lines

Aug 26 10:55:33 Error line.
Aug 26 10:58:12 Error line.

I am using AIX.

2

With a hat tip to Stéphane Chazelas for their two answers here:

I propose a brute-force solution that loops over every possible timestamp entry for the past 10 minutes:

#!/bin/ksh93
for((i=0;i<=600;i++))
do
  d=$(printf '%(%b %d %H:%M:%S)T\n' "$i seconds ago")
  grep "^${d} Error" logfile
done

It's brute-force because it calls grep (and printf, a built-in) 601 times. It requires a ksh93 that supports the printf %T option for printing (and formatting) arbitrary timestamps. It's easier than doing date math on your own, though, because of edge cases such as:

  • day boundaries
  • month boundaries
  • possible daylight-savings changes
1

A possibility here, shamelessly ripping off @Jeff Schaller's solution. Single invocation of grep, so maybe a little faster.

#!/bin/ksh93
for((i=0;i<=600;i++))
do
  d=$(printf '%s|%(%b %d %H:%M:%S)T' "${d}" "${i} seconds ago")
done
grep -E "^(${d:1}) Error" logfile
0

Thanks for all your responses i did the required work with following command.

awk -v d1="$d1" -v d2="$d2" '$0 > d1 && $0 < d2 || $0 ~ d2' logfile

where d1 and d2 were initialized above. Did the job for me.

Cheers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.