in reply to Print 5 lines before and after pattern match from a list

Edit: I managed to create a dummy file that printed according to what jayu_rao wanted, despite the double use of the counter noticed by hdb!

----original post below----

Are your caught lines not just too close together? Try adding the marker and counter that I put in below and look at the results. Also, if you make the match case insensitive you can compress the first three patterns into one. I tested it with the dummy file in the spoiler:

# dummy log file .*Error.*1 stuff1 stuff2 .*Error.*2 stuff3 stuff4 stuff5 stuff6 stuff7 stuff8 stuff9 .*Error.*3 stuff10 .*Error.*4 stuff11 stuff12 stuff13 stuff14 stuff15 stuff16 stuff17 stuff18 stuff19 .*Error.*5 stuff20 stuff21 stuff22 stuff23 stuff24 stuff25 stuff26
#!/usr/bin/env perl use strict; use diagnostics; open my $read_log, '<', '/home/jayu_rao/test_output/app.log' or die $! +; open my $write_tmp_app_log, '>', '/home/jayu_rao/test_output/write_tmp +_app.log' or die $!; my @patterns = ( qr/.*Error.*/, qr/.*error.*/, qr/.*ERROR.*/, qr/.*FATAL.*/, qr/.*Critical.*/, qr/.*exception.*/, ); my @lines=<$read_log>; my $i; my $counter=0; for (@patterns){ for $i (0..$#lines) { next unless $lines[$i] =~ $_; my $a = $i - 5 < 0 ? 0 : $i - 5;; my $b = $i + 5 > $#lines ? $#lines : $i + 5; for $i($a..$b){ print $write_tmp_app_log $lines[$i] }; $counter++; print $write_tmp_app_log "----------marker$counter------------"; } } close $read_log; close $write_tmp_app_log;