msensay has asked for the wisdom of the Perl Monks concerning the following question:

Hi folks, I'm looking to read in a file, search for a particular string and then pring the nth line before the line containing the match. The code below which prints lines before and after the match are getting to where I want to be, but I'm looking for something cleaner/easier or other better approaches to this. Thanks in advance!
use strict; use warnings; use Tie::File; sub max ($$) { $_[$_[0] < $_[1]] } sub min ($$) { $_[$_[0] > $_[1]] } my $file_in = 'data.txt'; my @lines; tie @lines, 'Tie::File', $file_in or die "Unable to tie $file_in $!"; my $n_recs = @lines; # how many records are in the file? my @lnbrs = (); my $i = 0; while ($i < $n_recs - 1) { my $twolines = $lines[$i] . $lines[$i + 1]; if ($twolines =~ m/file\s+for\s+(?:bankrup|chapter)/im) { push @lnbrs, $i } $i++; } foreach my $ln (@lnbrs) { my $start = max($ln-3, 0); my $end = min ($ln+3, $n_recs); <strong class="highlight">print</strong> '-' x 75, "\n"; foreach ($start .. $end) { <strong class="highlight">print</strong> "$lines[$_]\n"; } } untie @lines;

Replies are listed 'Best First'.
Re: find a match and pull nth line before the match
by JavaFan (Canon) on Mar 14, 2012 at 02:09 UTC
    Untested:
    my $N = ...; # Number of lines before matching line. my $PATTERN = "..."; # What you want to match. my @buffer; while (my $line = <>) { if (@buffer < $N) { push @buffer, $line; next; } if ($line =~ /$PATTERN/) { print $buffer[0]; } shift @buffer; push @buffer, $line; }
      Thanks JavaFan. That's exactly what I needed.
Re: find a match and pull nth line before the match
by BrowserUk (Patriarch) on Mar 14, 2012 at 02:20 UTC

    perl -nE"push @b,$_;say $b[0] if /pattern/;shift@b if @b >10;" file.in

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?