in reply to Print Lines above and below string
Well, if you found examples that print lines before the hit and examples that print lines after the hit, you could just combine them
Usually to print lines before a hit, you create a line storage where the previous 5 lines are stored. When you find the string print the previous lines from storage. To print 5 lines after a hit, just set a counter to 5 when you find it and print lines as long as the counter (that you decrement) is greater than 0. Both methods can be combined without any problems
But the simple algorithms have one drawback: They will reprint lines if these are in the vicinity of two hits. This might be just what you want. If not, use the following method: Have a storage of 5 lines and a counter you set to 10. Always print from the storage, but compare the searchstring with the line you just read. If you get a hit set the counter to 10. Again print and decrement
while ($line = <LOGFILE>) { push @storage, $line); if ($line =~ /$string_to_find/i) { $counter=10; } if (@counter-- and @storage>=5) { print shift @storage; } }
Untested
|
---|