Obligatory Tie::File solution. I haven't done any benchmarks, but I would guess it's as fast as the other Perl solutions while being less memory-intensive.

As others have said, /bin/grep is the way to go here.

#!/usr/bin/perl use strict; use warnings; use Tie::File; use Fcntl 'O_RDONLY'; my $DEBUG = 0; my $text = qr/c9391b56-b174-441b-921c-7d63/; my $file = 'GWSvc.log'; my $context = 3; sub dprint { print @_ if $DEBUG }; my @lines; tie @lines, 'Tie::File', $file, mode => O_RDONLY or die "tie failed: $!"; for (my $i = 0; $i <= $#lines; $i++) { dprint "SCAN: line $i\n"; if ($lines[$i] =~ /$text/) { dprint "MATCH at line $i\n"; my $start = $i - $context; if ($start < 0) { $start = 0; }; my $end = $i + $context; for my $j ($start .. $end) { dprint "$j: "; print "$lines[$j]\n"; }; print "\n"; $i += $context; }; };

In reply to Re: grab 'n' lines from a file above and below a /match/ by mrpeabody
in thread grab 'n' lines from a file above and below a /match/ by barathbr

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.