Comparing two files to get only records to be inserted and updated

Hello all,

Please help me for a script that compares two files and reads only those records that are to be inserted and updated.
File1:

c_id    name   place   contact_no
1         abc       xyz      34567
10       efg        uvw     82725
6         hjk        wth      01823
2         iuy       wqa      9876

File2:

c_id    name   place   contact_no
1         abc       xyz      34567
10       efg        uvw     77777
6         zzz        wth      01823
2         iuy       wqa      9876
3        axy         cde        3837

I want to create a file3 that would contain

c_id    name   place   contact_no
10       efg        uvw     77777
6         zzz        wth      01823
3        axy         cde        3837

I have used the command:

comm -13 <(sort file1) <(sort file2) >file3

But somehow null records are coming to file3 which is preventing its loading in database.And the header is appended in the last line of file3.

Can anyone please help me fixing the problem.

you can try the below

for i in `cat file2`
do
grep "$i" file1 >> file3
done

When I tried zozoo's script, it didn't come close to producing the requested output. (It is grepping for matching words instead of matching lines.) I think the following comes closer to what was requested:

awk '
FNR == NR {
        if(NR > 1) f1[$0]
        next
}
!($0 in f1) {
        print
}' file1 file2 > file3

If you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk .

thanks Don Cragun for trying and poiting out the error. if you use

while

loop and

grep 

combination then we can achieve the desired result.

Hi zozoo,
If we make some assumptions about the input that the original poster did not specify, then it might be possible to write a while read loop using grep to get the output specified in the 1st message in this thread, but I don't think it is as easy as you're implying.

Can you show us a while loop using grep that produces the output requested in the 1st message in this thread from the two input files shown in that message?