my %file1; while () { # Capture first four words, and everything after the next 3 words (numbers) my ($k1, $k2) = /(\w+(?:\s+\w+){3})(?:\s+\w+){3}(.*)/; # Index by k1, store k2 and line $file1{$k1} = [$k2, $_]; } while () { my ($k1, $k2) = .... # same regex as before if ($file1{$k1}) { # print file1 line and file2 line print $file1{$k1}->[1]; print; # Check if k2's are equal if ($file1{$k1}->[0] ne $k2) { print "K2's are not equal! (see lines printed above)\n"; } } }