#!/usr/bin/perl -w use strict; my $pattern1 = qr/encryption/; my $pattern2 = qr/encryption/; my $in_match = 0; while () { next unless /\S/; # Skip blank lines chomp; my ($command, $output) = split /\|/; if ($command =~ /\S/) { $in_match = $command =~ $pattern1; } if ($in_match and $output =~ $pattern2) { print $_, "\n"; } } __DATA__ Command | output show run in encryption | service password-encryption | fsddfsfsdfsdfsd sdfs sd | encryption | foo show ntp status | clock synchronised. 34.45.54.54 | some other text encryption1 | encryption2