Well, if you found examples that print lines before the hit and examples that print lines after the hit, you could just combine them

Usually to print lines before a hit, you create a line storage where the previous 5 lines are stored. When you find the string print the previous lines from storage. To print 5 lines after a hit, just set a counter to 5 when you find it and print lines as long as the counter (that you decrement) is greater than 0. Both methods can be combined without any problems

But the simple algorithms have one drawback: They will reprint lines if these are in the vicinity of two hits. This might be just what you want. If not, use the following method: Have a storage of 5 lines and a counter you set to 10. Always print from the storage, but compare the searchstring with the line you just read. If you get a hit set the counter to 10. Again print and decrement

while ($line = <LOGFILE>) { push @storage, $line); if ($line =~ /$string_to_find/i) { $counter=10; } if (@counter-- and @storage>=5) { print shift @storage; } }

Untested


In reply to Re: Print Lines above and below string by jethro
in thread Print Lines above and below string by coding_new

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.