in reply to Newbie Text Parsing Question
If the files are small, the easiest way to "back up" is to read the whole thing into memory. Something like this:
If the files are large, this could eat up lots of memory. In that case, you'll have to play games with backing up inside the file, which is trickier. (An exercise for the reader. ;-)# Loop over all files with a .log suffix foreach my $fn (<*.log>) { # Open the file, if possible, and read it all into @f open I, $fn or warn("Couldn't open $fn: $!"), next; my @f = <I>; close I; # Go through it a line at a time for (my $i = 0; $i < @f; $i++) { # If you find "hello" anywhere in the line, # Back up two lines and print if possible if ($f[$i] =~ /hello/) { print $f[$i-2] if $i > 1; print $f[$i-1] if $i > 0; print $f[$i]; } # Note, if you don't care about "undefined value" # warnings, print the three elements without any # condition. } }
HTH
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Newbie Text Parsing Question
by kanikilu (Initiate) on Jul 06, 2001 at 00:26 UTC | |
by kanikilu (Initiate) on Jul 06, 2001 at 00:39 UTC |