Skip to content
Advertisement

How to get all lines from one file which contain a string in another file?

File 1:

a
a
b
c
d

File 2:

a a1
b b1
e e1
f f1

My desired output:

a a1
a a1
b b1

I am trying to implement this using bash or Python.

In python I tried:

f1=open("file1")
f2=open("file2")
dpo1=f1.readlines()
dpo2=f2.readlines()

for i in dpo2:
    for j in dpo1:
        if j in i:
            print i

In bash I was thinking of using grep but grep will give the output that matches the entire line but this is not the case here. Any ideas?

Advertisement

Answer

This is what works finally.

awk 'NR==FNR{a[$1]=$2;next}$0 in a{print $0,a[$0]}' file2 file1
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement