my $tag; while(){ chomp; if(/([A-Z]{2}):$/){ $tag = $1; next; } if($tag eq 'AU'){ print "\n".$_; } if($tag eq 'BD'){ print ','.$_; } }