...## get $fh from somewhere (eg.open) my $last = ''; while( <$fh> ) { ( $last . $_ ) =~ m[cpuinfo\nvendor_id\s+:\s(.*?)\n] and print qq[CPU:$1] and last; $last = $_; } ... #### perl -ne"($last.$_)=~m[cpuinfo\nvendor_id\s+:\s(.*?)\n]&&print qq[CPU:$1]&&exit;$last=$_" yourfile