4

I have file A.txt which is a lists of unique ids (column 1) and its corresponding values(column 2):

A.txt

ABC1D_T1_B1  123.4
ABC2D_T1_B2  146.7
ABC3D_T1_B1  567.8
ABC4D_T0_B2  96.8
ABC1D_T0_B1  145.9

Second file is B.txt, not unique but has duplicated entries

ABC1D_T1_B1
ABC1D_T1_B1
ABC2D_T1_B2
ABC3D_T1_B1
ABC3D_T1_B1
ABC4D_T0_B2
ABC1D_T0_B1
ABC1D_T0_B1

How can I grep B.txt from A.txt and report the values of col 2 for the repeated list

Result:

ABC1D_T1_B1  123.4
ABC1D_T1_B1  123.4
ABC2D_T1_B2  146.7
ABC3D_T1_B1  567.8
ABC3D_T1_B1  567.8
ABC4D_T0_B2  96.8
ABC1D_T0_B1  145.9
ABC1D_T0_B1  145.9
ABC1D_T0_B1  145.9

Normally if unique entries are there in B.txt then

grep -Fw -f B.txt A.txt >Result.txt

How can I do this for multiple repeating entries using grep?

2 Answers 2

5

You could do it by using a simple join:

join A.txt B.txt

But, in order to work both files must be sorted on the join key (here the first (blank separated) field). To do it, just use sort -b filename.

1
  • Never thought that it could be so simple by just using join! Thanks Much!
    – Roli
    Dec 5, 2014 at 12:47
4

Since you have also tagged awk:

awk 'FNR == NR {a[$1] = $0; next}; {print a[$1]}' A.txt B.txt

I don't think a single grep can do this, but a combination of xargs and grep:

xargs -I{} grep -Fw -- {} A.txt < B.txt
2
  • @Steph curious: does the -w improve things? (I know OP is using it, but I am not sure if it's needed.)
    – muru
    Dec 5, 2014 at 12:46
  • 3
    @muru, without it, ABC1D_T1_B1 would match ABC1D_T1_B10. That's a bit better with -w, though ABC1D_T1_B1 would still match ABC1D_T1_B1.2 Dec 5, 2014 at 12:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .