3

I need to match two unequal files using $1 of file 1 and $2 of file 2 and print $1 of file 2 on file 1.

Input file 1

101 2
101 5
101 7
103 2
103 3
103 4
105 3
105 2

Input file 2

24 101
23 103
26 105

Desired output

101 2 24
101 5 24
101 7 24
103 2 23
103 3 23
103 4 23
105 3 26
105 2 26

I have tried the following code but it gave me incorrect output.

awk 'FNR==NR{a[$2]=$0;next};{print a[$2]}' file2 file1
3

A classic job for join:

join -1 1 -2 2 file1 file2
  • -1 1 specifies the field in the first file.
  • -2 2 specifies the field in the second file.
  • Notice, though, that this requires that the field you join on is sorted in both files (they happen to be in this instance). – Kusalananda Jan 13 '17 at 12:12
0

Starting from your code, I also post an awk solution because you were almost there:

awk 'FNR==NR { a[$2]=$1; next; } { print $0,a[$1] } ' file2 file1

Output:

101 2 24
101 5 24
101 7 24
103 2 23
103 3 23
103 4 23
105 3 26
105 2 26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.