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.

#!/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); }
Edit: above code is deficient both at the start and end of the stream. See if you can fix it...


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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.