Ismeet Kaur
Ismeet Kaur

Reputation: 63

Match list from one file1, extract corresponding lines form file 2

Suppose I have a reference list, say file1.txt, which contains:

a
b
c 
d

and I have file2.txt, the data file as follows:

a 1 2 3
b 5 6 7
d 6 7 8
e 7 8 9

and output needed in output.txt:

a 1 2 3
b 5 6 7
d 6 7 8

I want to match IDs in file1.txt with first column of file2.txt and print the whole line (row from file2.txt) into output.txt

Upvotes: 1

Views: 3044

Answers (2)

Chris Seymour
Chris Seymour

Reputation: 85825

This is what join is designed for:

$ join f1 f2
a 1 2 3
b 5 6 7
d 6 7 8

If you need to sort your files first then:

join <(sort f1) <(sort f2)

Upvotes: 7

Vijay
Vijay

Reputation: 67281

awk 'FNR==NR{a[$1];next}($1 in a)' file1.txt file2.txt

Also in perl :

perl -F -lane '$h{$F[0]}++;if($h{$F[0]}>=2){print $_;}' file1 file2

Note:The above perl command will work provided the first file has unique ID's

Upvotes: 4

Related Questions