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?
In awk
Will work if the string matches any field.
awk 'FNR==NR{a[$1]++;next}{for(i=1;i<=NF;i++)if(a[$i]){print;next}}' file{1,2}
a a1
b b1
For edit
awk 'FNR==NR{a[$1]++;next}{for(i=1;i<=NF;i++)if(a[$i]){for(j=1;j<=a[$i];j++)print;next}}' file{1,2}
a a1
a a1
b b1
这终于可以了。
awk 'NR==FNR{a[$1]=$2;next}$0 in a{print $0,a[$0]}' file2 file1
If files are not large, just do
dpo1 = [i.strip() for i in dpo1]
lines = [i.strip() for i in dpo2 if(any([j for j in dpo1 if j in i]))]
>>>lines
['a a1', 'b b1']
>>>for i in lines:
... print i
'a a1'
'b b1'
f1=open("file1")
f2=open("file2")
dpo1=f1.readlines()
dpo2=f2.readlines()
for x in dpo2:
for y in dpo1:
if y.strip() in x:
print x.strip()
break
For each line in dpo2(source file, which generate the outputs), test if it contains one of line in dpo1(conditional file). If we get a match, print it and break for next line in dpo2.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.