# First build a hash we can use to look up lines (keyed on 2nd line) my %pairs; open A, ") { $pairs{}=$_ } close A; # We use a third file open C, ">C"; open B, ") { # If this line matches a known 2nd line, insert it's 1st print C $pairs{$_} if exists $pairs{$_}; # Always print the original line print C $_; } close B; close C;