
Untitled
By: a guest on
Apr 25th, 2012 | syntax:
None | size: 2.12 KB | hits: 19 | expires: Never
Comparing two directories using Perl
$ perl dirComp.pl dir1 dir2
Store all the contents of dir1(recursively) in a list
Store all the contents of dir2 in another list
Compare the two list, if they are same - dir1 & dir2 are same else not.
my @files1 = readdir(DIR1h);
my @files2 = readdir(DIR2h);
# Remove filename extensions for each list.
foreach my $item (@files1) {
my ( $fileName, $filePath, $fileExt ) = fileparse($item, qr/.[^.]*/);
$item = $fileName;
}
foreach my $item (@files2) {
my ( $fileName, $filePath, $fileExt ) = fileparse($item, qr/.[^.]*/);
$item = $fileName;
}
#!/usr/bin/perl -w
use File::DirCompare;
use File::Basename;
if ($#ARGV < 1 )
{
&usage;
}
my $dir1 = $ARGV[0];
my $dir2 = $ARGV[1];
File::DirCompare->compare($dir1,$dir2,sub {
my ($a,$b) = @_;
if ( !$b )
{
printf "Test result:PASSED.n";
printf "Only in %s : %sn", dirname($a), basename($a);
}elsif ( !$a ) {
printf "Test result:PASSED.n";
printf "Only in %s : %sn", dirname($b), basename($b);
}else {
printf "Test result:FAILED.n";
printf "Files $a and $b are different.n";
}
});
dir1/ dir2/
--file1.txt --file1.txt
--file2.txt --file2.txt
--file3.cpp --file3.cpp
use strict;
use warnings;
use feature qw(say);
use Digest::MD5::File qw(file_md5_hex);
use File::Find;
use constant {
DIR_1 => "/usr/foo",
DIR_2 => "/usr/bar",
};
my %dir_1;
my %dir_2;
find ( sub {
if ( -f $File::Find::name ) {
$dir_1{$File::Find::name} = file_md5_hex($File::Find::name);
}
else {
$dir_1($file::Find::name} = "DIRECTORY!";
}
}, DIR_1);
find ( sub {
if ( -f $File::Find::name ) {
$dir_2{$File::Find::name} = file_md5_hex($File::Find::name);
}
else {
$dir_2($file::Find::name} = "DIRECTORY!";
}
}, DIR_2);
/usr/bar/my/file/is/here.txt
/usr/foo/my/file/is/here.txt