I can think of two approaches off the top of my head, other monks will likely have MTOWTDI:

1. Read multiple lines at a time (if your files aren't too big, just read the whole file), write a regex that matches your pattern and also captures the lines before and after your pattern. Writing a regex that matches multiple lines is not too difficult once you've read about the following topics in perlre: the /m and /s modifiers, and the exact meaning of ^, $, ., \s and \n. Also, see I'm having trouble matching over more than one line. What's wrong?

Here's a somewhat inelegant regex that captures the lines before and after a match:

my $input = "line1\nline2\nline3 foo\nline4\nline5"; my ($before,$match,$after) = $input=~/^ (?:(.*)\n)? (.*foo.*) (?:\n (? +:(.*)\n?)? )? /xm; print "before=<$before>, match=<$match>, after=<$after>\n";

2. Keeping a buffer of lines, i.e. an array which always contains the most recent N lines. Such an array could be managed via push and shift. In other words, a sliding window of sorts. This approach would probably be considered less "perlish" than the first, but might be more efficient on large files. Actually, Tie::File may be better than managing the array yourself.

InfiniteSilence just posted an answer that uses the array approach.


In reply to Re: Grab 3 lines before and 2 after each regex hit by Anonymous Monk
in thread Grab 3 lines before and 2 after each regex hit by HarryPutnam

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.