Hello Mjpaddy,
Really nicely pointed out by Anonymous Monk (DIFF), under the assumption that you are running a Linux OS. I you are not running Linux an alternative would be to install Cygwin and execute the commands through there, or simply with the command FC file_1 file_2. More information can be found here fc.
Also a Perl solution by Athanasius the (Text::Diff).
But I could resist posting another alternative solution, that I found extremely useful not only comparing files but also for general purposes.
The Array::Utils module where you compare arrays. It provides you with the ability to compare elements of each array.
Sample of file_1.txt based on your description.
This is line 1. Another line number 2. This is also another line 3.
Sample of file_2.txt based on your description.
This is line 1. Another line number 5. This is also another line 3.
Finally the code with the output based only two options. Read the module it can provide you with alternative output, I choose these two for demonstration purposes.
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Array::Utils qw(:all); my $file_1 = "sample-1.txt"; my $file_2 = "sample-2.txt"; my $file_3 = "error.txt"; open (my $in_1, "<" , $file_1) or die "Could not open: ".$file_1." - $!\n"; open (my $in_2, "<" , $file_2) or die "Could not open: ".$file_2." - $!\n"; open (my $out, ">>" , $file_3) or die "Could not open: ".$file_3." - $!\n"; my @data_1 = <$in_1>; chomp(@data_1); my @data_2 = <$in_2>; chomp(@data_2); # symmetric difference my @diff = array_diff(@data_1, @data_2); print Dumper(\@diff); # get items from array @data_1 that are not in array @data_2 my @minus = array_minus( @data_1 , @data_2 ); print Dumper(\@minus); foreach $_ (@diff) { print $out $_ . "\n"; } foreach $_ (@minus) { print $out $_ . "\n"; } #print $out @diff; #print $out @minus; close ($in_1) or die ("Could not close: ".$file_1." - $!\n"); close ($in_2) or die ("Could not close: ".$file_2." - $!\n"); close ($out) or die ("Could not close: ".$file_3." - $!\n"); __END__ $VAR1 = [ 'Another line number 2.', 'Another line number 5.' ]; $VAR1 = [ 'Another line number 2.' ];
Hope this helps.
In reply to Re: Perl: How to compare two files
by thanos1983
in thread Perl: How to compare two files
by Mjpaddy
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |