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