while (my $line=<$fh>) { # assuming a loop through your file here my ($nm_xp) = $line =~ /Homo sapiens.*\s(NM_\w*|XP_\w*)/; next unless $nm_xp; print "$nm_xp for a great ape found at line $.\n"; }