1834135 Members
2144 Online
110064 Solutions
New Discussion

Comparing Two Text Files

 
SOLVED
Go to solution
pareshan
Regular Advisor

Comparing Two Text Files

I am writting a script where I have to Campare two text files.
I have 3 text files named by s_list, s_list_new and dmg_file. where I have to compare s_list and s_list_new and whatever the unique values are in s_list I have to add that in the dmg_file. And the values they are only in s_list_new and not in s_list I have to delete that from dmg_file

I have tried so many things, but diff, comm is not helping me because if i do comm it compares line by line and the value may not match line by line and with diff its not giving me exact output and I am thinking may be im not aware of different diff output formats.
for example if i do diff temp temp1 i get like this output and I dont want it. i just want thos unique values nothing else

diff temp temp1
1,5d0
< a
< 1
< 2
< 3
< 4
11c6,9
<
---
> 10
> 11
> 12
> 13


Any Help Plz
I will appreciate the help
5 REPLIES 5
Steven Schweda
Honored Contributor

Re: Comparing Two Text Files

First "sort", then "diff"?
James R. Ferguson
Acclaimed Contributor

Re: Comparing Two Text Files

Hi:

You might find:

# diff -c file1 file2

...quite useful. See the manpages for 'diff'.

Regards!

...JRF...
Ivan Krastev
Honored Contributor

Re: Comparing Two Text Files

Use grep:

grep -vf file1 file2

regards,
ivan
Dennis Handly
Acclaimed Contributor
Solution

Re: Comparing Two Text Files

As Steven partially said, you need to use sort and comm(1). My script will also sort dmg_file.

# sort for comm
sort s_list > s_list.s
sort s_list_new > s_list_new.s

# add unique stuff to dmg_file
comm -23 s_list.s s_list_new.s >> dmg_file
# get unique stuff to remove
comm -13 s_list.s s_list_new.s > dmg_file.r

# sort for comm
sort dmg_file > dmg_file.s
# Remove stuff that was in s_list_new
comm -13 dmg_file.r dmg_file.s > dmg_file
# cleanup
rm -f s_list.s s_list_new.s dmg_file.[rs]

>Ivan: grep -vf file1 file2

Caution about grep, you need to use -x and may need fgrep instead if comparing whole lines.
Shahul
Esteemed Contributor

Re: Comparing Two Text Files

Hi,

You can do this with a combination of commands "diff" and "comm". Please see the man page for both.

Good luck
Shahul