in reply to Get specified number of previous line text when encountered a text match in a file

As an alternative, you can take a look at Tie::File. This would let you handle the file as an array. Here's a completely untested piece of code, just to give you the idea:
tie @l, "Tie::File", $file or die $!; for my $i (0 .. $#l) { if ($l[$i] =~ /Error Occurred/) { while($i > 0) { $i--; if ($l[$i] =~ /(A|B):\d+/) { print $l[$i]; exit; # or last } elsif ($l[$i] =~ /^====/) { exit; # or last } } } }
However, Tie::File is not that efficient on large files.

Another alternative could use a combination of a normal filehandle to go forward in the file, and File::ReadBackwards to go backward in the same file.

  • Comment on Re: Get specified number of previous line text when encountered a text match in a file
  • Download Code