while (){ if (/(.*)<\/text>/) {$currentheader = $1} # if the current line has a header, save it, otherwise, keep last saved header # your data search code goes here if (there was a hit) {print $currentheader along with the hit} }