Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I compare the content of 2 files with perl?

Status
Not open for further replies.

Sina

Technical User
Jan 2, 2001
309
CA
Hello everyone.

How can I compare the content of 2 files.
file content:

file1:

123
456
985
345

file2:
123
456
876
000

How can I compare these 2 files and report on the differences?

Thank you all for your help
 
The following will work as long as the files contain the same amount of lines.
Code:
$file1 = "file1";
open(F, "$file1") or die "Can't open $file1: $!\n";
@lines1 = (<F>);
close(F);
$file2 = &quot;file2&quot;;
open(F, &quot;$file2&quot;) or die &quot;Can't open $file2: $!\n&quot;;
@lines2 = (<F>);
close(F);
foreach $i (0..@lines1) {
    next if ($lines1[$i] eq $lines2[$i]); 
    print &quot;difference at line &quot;, $i+1, &quot;:\n&quot;;
    print &quot;    file1: $lines1[$i]&quot;;
    print &quot;    file2: $lines2[$i]&quot;;
}
 
Thank you so very much I will try that at home.

thanks
 
Just one thing. the files may have different number of lines. One file may have 1000 lines and the other 1200 lines.

However both are sorted and for the first 1000 lines should at least be the same, you know what I mean.

Would this still work.?

I hope I'm clear.

But thank you so much. I will try this and let you know.
 
Yes it will work :

Code:
foreach $i (0..@lines1)
This lines means that the application look every lines of the first file but stop when it will end.
 
Shouldn't that be $#lines1 rather than @lines1? If you want $i to run from 0 to the last element in the array you want $#lines1. Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Hi raider2001.
First of all thanks so very much.
But I need to be more clear.
Your program works prefect if both files have identical strings at identical line numbers.
but in my case

file 1:

23
786
453
56

file 2:

888
999
453
23
9990
7776
So basically I have to print the differences between these two files in a file (in a way that show this difference is coming either from file 1 or 2).
for example:

output file after comarison.:
file1:line #2 &quot;786&quot; does not exist in file 2
file2:line #1 &quot;888&quot; does not exist in file 1.

Can you or anybody help.
Thanks very much.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top