hprakash
hprakash

Reputation: 472

comparing files to find difference between them in ruby returns wrong result.

I'm trying to compare two text file and write their difference into another text file. but im getting wrong differences. that is, name which is existing in both the files are also coming under difference file.

Im using this code, which i got from stackoverflow.

#new file
f1 = IO.readlines("file1.txt").map(&:chomp)
#old file
f2 = IO.readlines("file2.txt").map(&:chomp)

File.open("result.txt","w"){ |f| f.write("NEED TO ADD:\n")}
File.open("result.txt","a"){ |f| f.write((f1-f2).join("\n")) }
File.open("result.txt","a"){ |f| f.write("--------------------\n")}
File.open("result.txt","a"){ |f| f.write("NEED TO REMOVE:\n")}
File.open("result.txt","a"){ |f| f.write((f2-f1).join("\n")) }

and i have the following content in my file1.txt and file2.txt

file1.txt contains:

colors  
channel [v]     
star plus   
star utsav  
sony
life ok             
zee salaam
zee tv      
nepal one   
zee anmol                
flowers tv   

file2.txt contains:

colors
sony entertainment
star plus
star utsav
zee tv
life ok
dd national
etc bollywood
zee anmol 

and my result.txt file contains:

NEED TO ADD:
colors  
channel [v]     
star plus   
star utsav  
sony
life ok             
zee salaam
zee tv      
nepal one   
zee anmol                
flowers tv   
---------------------------------------------------
NEED TO REMOVE:
colors
sony entertainment
star plus
star utsav
zee tv
life ok
dd national 
etc bollywood
zee anmol 

i hope you can understand my problem from the result file. help me with a direct answer as im a newbie.

Upvotes: 1

Views: 251

Answers (1)

lime
lime

Reputation: 7111

It looks like you have trailing whitespace in file1.txt, which causes the differences.

E.g. "colors " is not equal to "colors", causing them to be listed in different sections.

If you want to strip away all leading and trailing whitespace before comparing lines, you can use .strip:

f1 = IO.readlines("file1.txt").map(&:strip)
f2 = IO.readlines("file2.txt").map(&:strip)

That should produce the result you expected, even if you accidentally have some trailing whitespace.

Upvotes: 1

Related Questions