in reply to grab 'n' lines from a file above and below a /match/
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; }; };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: grab 'n' lines from a file above and below a /match/
by Aristotle (Chancellor) on Sep 17, 2004 at 06:23 UTC | |
by mrpeabody (Friar) on Sep 20, 2004 at 03:07 UTC |