use strict; use warnings; my ( $prevLine, $nextLine ); for ( ; ; ) { last if eof DATA; chomp( my $currLine = defined $nextLine ? $nextLine : ); if ( $currLine =~ /match this/ ) { print '-' x 25, "\n"; chomp( $nextLine = ) if !eof DATA; print $prevLine, "\n" if defined $prevLine; print $currLine, "\n"; print $nextLine, "\n" if defined $nextLine; print '-' x 25, "\n"; } else { undef $nextLine; } $prevLine = $currLine; } __DATA__ The first line match this Not this abcdefg The one above Another match this 1 Another match this 2 the one below match this 2 zxcvbnn Another match this blank above Second to the last line The last line match this #### ------------------------- The first line match this Not this ------------------------- ------------------------- The one above Another match this 1 Another match this 2 ------------------------- ------------------------- Another match this 1 Another match this 2 the one below match this 2 ------------------------- ------------------------- Another match this 2 the one below match this 2 zxcvbnn ------------------------- ------------------------- Another match this blank above Second to the last line ------------------------- ------------------------- Second to the last line The last line match this ------------------------- #### use strict; use warnings; my ( $prevLine, $nextLine, %printed ); for ( ; ; ) { last if eof DATA; chomp( my $currLine = defined $nextLine ? $nextLine : ); if ( $currLine =~ /match this/ ) { chomp( $nextLine = ) if !eof DATA; print $prevLine, "\n" if defined $prevLine and !$printed{$prevLine}++; print $currLine, "\n" if !$printed{$currLine}++; print $nextLine, "\n" if defined $nextLine and !$printed{$nextLine}++; } else { undef $nextLine; } $prevLine = $currLine; } __DATA__ The first line match this Not this abcdefg The one above Another match this 1 Another match this 2 the one below match this 2 zxcvbnn Another match this blank above Second to the last line The last line match this #### The first line match this Not this The one above Another match this 1 Another match this 2 the one below match this 2 zxcvbnn Another match this blank above Second to the last line The last line match this