msensay has asked for the wisdom of the Perl Monks concerning the following question:
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 | |
by msensay (Novice) on Mar 14, 2012 at 19:31 UTC | |
|
Re: find a match and pull nth line before the match
by BrowserUk (Patriarch) on Mar 14, 2012 at 02:20 UTC |