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
In reply to Re: Newbie Text Parsing Question
by VSarkiss
in thread Newbie Text Parsing Question
by kanikilu
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |