Here's a filter version (read from stdin, write to stdout) of this, um, filter. I've also added the before/after context parameters as program options. (Consistent with the grep utility.)
Note the use of a small queue (@lines) to buffer the before-context. And notice the versatility of the splice function.
Edit: above code is deficient both at the start and end of the stream. See if you can fix it...#!/usr/bin/env perl use strict; use warnings; use Getopt::Std; my @patterns = ( qr/error/i, qr/FATAL/, qr/Critical/, qr/exception/, ); my $re = join '|', @patterns; my %opt = ( B => 5, A => 5 ); getopts('B:A:', \%opt); my $window = $opt{B} + $opt{A} + 1; my $emit = 0; my @lines; while (<>) { $emit = $window if /$re/; splice(@lines, 0, 0, $_); --$emit < 0 ? splice(@lines, $opt{B}) : print splice(@lines, -1); }
In reply to Re: Print 5 lines before and after pattern match from a list
by oiskuu
in thread Print 5 lines before and after pattern match from a list
by jayu_rao
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |