Istvan
Istvan

Reputation: 8562

How to merge two files with unique IDs?

I have two files. File1 and File2.

File1:

1 a
2 b

File2:

1 a
2 c
3 d

I would like to generate a file that has the following:

1 a
2 c
3 d

The lines that File2 has either inserted or updated into File1, sort of how the UPSERT feature works in SQL.

Upvotes: 0

Views: 238

Answers (1)

Fredrik Pihl
Fredrik Pihl

Reputation: 45662

I'm guessing here, since question is a bit vague. Anyway, here's something in awk that just uses the first value as a key to store the 2nd value. 2nd value always overwrites content in array if the key is found multiple times:

$ awk '{a[$1]=$0}END{for (i in a) print a[i]}' f1 f2
1 a
2 c
3 d

EDIT: The new version takes an arbitrary wide file instead of being tied to two fields.

Upvotes: 2

Related Questions