$ echo "first line second line third line you have to read the fourth line one two three four five six you have to read the second line one two three" | perl -e' my %lookup = qw/ fourth 4 second 2 /; while ( <> ) { if ( /you have to read the (\w+) line/ && exists $lookup{ $1 } ) { $lines{ $. + $lookup{ $1 } }++; } if ( $lines{ $. } ) { print; } } ' four two