Bash – grep for repeated values from pattern list

awkbashgrep

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?

Best Answer

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
Related Question