Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining two files based on the first columns and preserving order

Tags:

unix

How can I join two files based on their first columns and preserving the order from the second file.. 

File 1:

ID1 123
ID2 234
ID3 232
ID4 344
ID5 345
ID6 867

File 2

ID2 A C
ID3 G T
ID1 C T
ID4 A C
...

So the merged file should look like this:

ID2 234 A C 
ID3 232 G T 
ID1 123 C T 
ID4 344 A C 
...

The IDs are the values of the first column (present in both files). File 1 has more rows/IDs than file 2. All IDs from file 2 are in file 1, but not all IDs from file 1 are in file 2

like image 835
anbu selvan Avatar asked Nov 17 '25 12:11

anbu selvan


1 Answers

Here's one way using awk:

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

Results:

ID2 234 A C
ID3 232 G T
ID1 123 C T
ID4 344 A C
like image 171
Steve Avatar answered Nov 20 '25 13:11

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!