Operating System - HP-UX
1748261 Members
3610 Online
108760 Solutions
New Discussion юеВ

Perl Question Reading Log File

 
SOLVED
Go to solution
Jason Berendsen
Regular Advisor

Perl Question Reading Log File

Is there a way in Perl to read a log file and key on a phrase, then read the next two lines after the phrase.

example-
ERROR: There was a problem
USER: This user caused the problem
DATE: Todays date and time

I would like to key on ERROR, but I also want the USER and DATE. I know how to do this with awk, but I want it portable to Windows. So I figure Perl would be more portable. Can anyone give an example of how to do this if it is possible.

Thanks,

Jason Berendsen
4 REPLIES 4
Rodney Hills
Honored Contributor

Re: Perl Question Reading Log File

How about-

perl -ne '/ERROR:/ && do {$cnt=3;} ; print $_ if $cnt--' yourlogfile

-- Rod Hills
There be dragons...
Tim Grantham
Occasional Contributor

Re: Perl Question Reading Log File

Rob,

I must be doing something wrong. Here is the test file I am using:

This shouldn't show line 1
This shouldn't show line 2
This shouldn't show line 3
This shouldn't show line 4
ERROR: There was a problem
USER: This user caused the problem
DATE: Todays date and time
This shouldn't show line 8
This shouldn't show line 9
This shouldn't show line 10
This shouldn't show line 11

I am hoping only to pull lines 5 thru 7. This is the output I get from your logic:

This shouldn't show line 2
This shouldn't show line 3
This shouldn't show line 4
ERROR: There was a problem
USER: This user caused the problem
DATE: Todays date and time
This shouldn't show line 9
This shouldn't show line 10
This shouldn't show line 11

Lines 1 and 8 are missing but 2,3,4,9,10 and 11 still show. Is there a way to just have the ERROR: line as well as the two lines after it?

Thanks for the help,

Jason
Rodney Hills
Honored Contributor
Solution

Re: Perl Question Reading Log File

You're right, I forgot $cnt is decrementing on all lines. This will fix it-

perl -ne '/ERROR:/ && do {$cnt=3;} ; print $_ if $cnt && $cnt--' yourinput

-- Rod Hills
There be dragons...
Jason Berendsen
Regular Advisor

Re: Perl Question Reading Log File

Thanks Rod it does exactly what I need!