neurotoxx has asked for the wisdom of the Perl Monks concerning the following question:
How can I search for a pattern in a log file, and then print the three lines before the line that has the matched pattern? For example:
Log file:
log info line yada yada 1 log info line yada yada 2 log info line yada yada 3 log info line (pattern) 4 log info line yada yada 5 ...
Results file:
log info line yada yada 1 log info line yada yada 2 log info line yada yada 3 (pattern) (Put line number here, or some type of result mark) ...
Here's the code I'm working with so far.
open(INFILE, "< file.log") or die "Cant open file : $!"; open(OUT, "> results.txt") or die "Cant open new file : $!"; $pattern = "Error code 2"; while (<INFILE>) { $a[$i++%3] = $_; print OUT $a[$i%3] if /$pattern/; } close INFILE; close OUT;
I saw a thread regarding the use of the "%3", but not sure how to use it correctly.
Please let me know how I could produce a result file that pulls the three lines prior to the match of the search string line.
Thank you in advance for any help that can enlighten me
-neurotoxx
|
---|