I am wanting to print 5 lines before and after a pattern match from a list. I have written the below code but its repeating the loop improperly and writing the lines more than once.
I am sure I am doing something silly but not able to figure it out. Can you anyone of you please help?
#!/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; 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] }; } } close $read_log; close $write_tmp_app_log;
In reply to Print 5 lines before and after pattern match from a list by jayu_rao
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |