in reply to Print Lines above and below string

So you want the context of the matched string. You will need to keep a rolling window of the last few lines you've seen. Actually, if your input isn't huge, just slurp up into an array, like so (untested):

open LOGFILE, "<$file"; @lines = <LOGFILE>; for my $i (0..$#lines) { next unless $lines[$i] =~ /$string_to_find/i; my $a = $i - 5 < 0 ? 0 : $i - 5;; my $b = $i + 5 > $#lines ? $#lines : $i + 5; print $lines[$_i] for my $_i ($a..$b); }

Replies are listed 'Best First'.
Re^2: Print Lines above and below string
by coding_new (Sexton) on Aug 10, 2011 at 15:39 UTC

    Thanks for the input. Few questions. My file sizes will be around 2.5 megs max. Not sure if that's a problem or not. Also once I ran the script you provided, I got an error on the last line

    Here is the error: syntax error at ./readlog5.pl line 12, near "$_i ("

Re^2: Print Lines above and below string
by ww (Archbishop) on Aug 10, 2011 at 22:19 UTC

    ++ for "Close!" ...but "untested" lets typos slip by:

    open (LOGFILE, "<$file") or die "Can't open $file"; my @lines = <LOGFILE>; my $lines; my $i; for $i(0..$#lines) { next unless $lines[$i] =~ /$string_to_find/i; my $a = $i - 5 < 0 ? 0 : $i - 5;; my $b = $i + 5 > $#lines ? $#lines : $i + 5; for $i($a..$b) { print $lines[$i]; } }
Re^2: Print Lines above and below string
by Anonymous Monk on Mar 24, 2016 at 09:12 UTC
    what $#lines does? would anyone please me