in reply to Delete 10 lines before matched line


Here is a one way to do it:
#!/usr/bin/perl use strict; use warnings; my @buffer; my $buffer_size = 10; my $match = qr/toolerror/; # Read a file from STDIN. while ( my $line = <> ) { if ( $line =~ /$match/ ) { # Discard the buffered lines. @buffer = (); # Print the matched line. print $line; } else { # Store non matching lines in a buffer. push @buffer, $line; # Maintain the buffer at a max size. if ( @buffer > $buffer_size ) { print shift @buffer; } } } # Print any remaining buffered lines. print @buffer; __END__

--
John.

Replies are listed 'Best First'.
Re^2: Delete 10 lines before matched line
by ikegami (Patriarch) on Mar 11, 2010 at 15:49 UTC
    # Discard the buffered lines. @buffer = (); # Print the matched line. print $line;
    should be
    # Discard the buffered lines. @buffer = $line;

      Yes it should.

      I thought of that and thought that the OP probably didn't want the matched line deleted or they would have said so. In which case I thought that they would only want 10 lines or less deleted back to the last match. Which leaves me doing a lot of ass of you and me-ing.

      However, your modification is definitely more correct in the general case.

      --
      John.

        thanks John it worked. in the while loop you are reinitializing the buffer so that In the else loop it goes and prints the contents ..Iam still learning perl, so can you please let me know if I have understood something wrong.