#!/usr/bin/perl use strict; use warnings; my (%patts, $f2_rec, $f2_field); my $f1 = $ARGV[0]; my $f2 = $ARGV[1]; open(my $fh1,"<", $f1) or die "Failled to open '$f1' $!"; while (<$fh1>) { chomp; next if /^\s*$/; $patts{substr $_, 0, 3} = 1; } close($fh1) or warn "Failled to close '$f1' $!"; open(my $fh2,"<", $f2) or die "Failled to open '$f2' $!"; while (defined ($f2_rec = <$fh2>)) { chomp $f2_rec; next if $f2_rec =~ /^\s*$/; $f2_field = (split(/ /,$f2_rec))[1]; $f2_field = substr $f2_field, 0, 3; if(exists($patts{$f2_field})) { print "$f2_rec\n"; } } close($fh2) or warn "Failled to close '$f2' $!"; # update changing open to close thank to Laurent_R for pointing out __END__ $ perl test.pl file1.txt file2.txt ID121 ABC14 ID122 EFG87 ID145 XYZ43 ID157 TSR11 ID181 ABC31 ID529 EFG56 ID684 TSR07