Merging two files by comparing three fields

June 6, 2009 at 14:07:06
Specs: Unix
Hi Experts,

I need your timely help. I have a problem with merging two files. Here my
situation :

Here I have to compare first three fields from FILE1 with FILE2. If they
are equal, I have to append the remaining values from FILE2 with FILE1
to create the output.

FILE1:
Class Category Item Field1 Field2 Field3
Class1 Sports Ball 11 12 13
Class2 Academic Bat 21 22 23
Class3 Academic Pen 31 32 33
Class4 Gift Birthday 41 42 43

FILE2:
Class Category Item Field4 Field5
Class1 Sports Ball 14 15
Class2 Academic Bat 24 25
Class3 Academic Pen 34 35
Class5 Books Maths 54 55

OUTPUT FILE (FILE3) :

Class Category Item Field1 Field2 Field3 Field4 Field5
Class1 Sports Ball 11 12 13 14 15
Class2 Academic Bat 21 22 23 24 25
Class3 Academic Pen 31 32 33 34 35
Class4 Gift Birthday 41 42 43 0 0


Your valuable suggestions are highly appreciated. Thankyou very much.

PS : If it contains only one field to compare from both file, "Join"
command would help to create the output.

join -a1 -e "0" FILE1 FILE2

A will always finds a way.


See More: Merging two files by comparing three fields

Report •


#1
June 8, 2009 at 04:34:26
if you have Python

f=open("file2")
fi=f.readline()
f1={}
for line in f:
    line=line.strip().split()
    f1.setdefault( ' '.join(line[:3]), ' '.join(line[3:] ) )
f.close()
f=open("file1")
fi=f.readline()
for line in f:
    line=line.strip().split()
    key=' '.join(line[:3])
    try:
        print ' '.join(line),f1[key]
    except: pass

output
# ./test.py
Class1 Sports Ball 11 12 13 14 15
Class2 Academic Bat 21 22 23 24 25
Class3 Academic Pen 31 32 33 34 35
Class4 Gift Birthday 41 42 43



Report •

#2
June 8, 2009 at 06:01:00
Hi Ghostdog,

Sorry for not putting this. I am using -ksh.
I would be more happy If i get the output in shell script and I need the first three fields to be compared and then the values must be appended.

Can we acheive this by "awk"?

Thankyou very much for considering this.

A will always finds a way.


Report •

Related Solutions


Ask Question