Comparing files

Hi All,
I want to compare two files which looks like this
File1: -

A 5
B 4
C 3
D 2

File2: -

C 10
A 8
D 7
B 6

Now these files are to be compared in a way that from first file's A's corresponding value is to be subtracted from 2nd files value which is corresponding to A, i;e 8-5 should be done and then B's corresponding value from file 1 is to be subtracted from the B's corresponding value in the file 2 i;e 6-4 and the O/P should be some thing like this

A 3
B 2
C 7
D 5

Please help me how to do this.
Thanks in Advance

You can do something like that :

awk '
NR==FNR { s[$1] = $2; next }
{ print $1,$2-s[$1] }
' File1 File2 | sort

Jean-Pierre.

 
#!/bin/bash
read file1
read file2
while read line 
do
 n1=`echo $line | awk '{ print $2 }'`
 l1=`echo $line | awk '{ print $1 }'`
 n2=`grep ^${l1} $file2 | awk '{ print $2 }'`
 echo $l1 `expr $n2 - $n1`
done < $file1

Optimize a little bit your script

#!/bin/bash
while read l1 n1 filler
do
   n2=$(awk "/^$l1/ { print \$2 }" File2)
   echo $l1 $((n2-n1))
done < File1

The technique used in your solution is not performant for large files, File2 is opened and read for each record of File1.

Jean-Pierre.

Yep, your right, it�s a little bit terrible.

For big files (assume unsorted) you can also do something like that :

sort File2 > /tmp/File2.sorted
sort File1 | \
join -a 1 -a 2 -o 0,1.2,2.2 -e 0 - /tmp/File2.sorted | \
while read l1 n1 n2
do
   echo $l1 $((n2 - n1)) 
done 
rm /tmp/File2.sorted

File1

A 5
B 4
C 3
D 2
XX 1

File2

C 10
A 8
D 7
B 6
YY 1

Output:

A 3
B 2
C 7
D 5
XX -1
YY 1

Jean-Pierre.