Advertisement
dpino

Compare files in two folders

Jul 2nd, 2013
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.71 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3.  
  4. # Compares all the files in two folders. Comparison is done using md5 signature.
  5. #
  6. # AUTHOR: Diego Pino García <dpino@igalia.com>
  7.  
  8. use strict;
  9.  
  10. open ERROR, ">.compare_errors" || die("Couldn't create .compare_errors");
  11. open LOG, ">.log" || die("Couldn't create .log");
  12.  
  13. my $dir1 = $ARGV[0] || ".";
  14. my $dir2 = $ARGV[1] || ".";
  15.  
  16. debug("$dir1, $dir2");
  17.  
  18. my @files = @{readfiles($dir1)};
  19. debug("total files: ".scalar(@files));
  20. compare($dir1, $dir2, @files);
  21.  
  22. close ERROR;
  23. close LOG;
  24.  
  25. sub md5
  26. {
  27.     my $filedir = shift;
  28.     my $str = `md5sum $filedir | cut -d " " -f 1`;
  29.     $str =~ s/\n//g;
  30.     return $str;
  31. }
  32.  
  33. sub debug
  34. {
  35.     my $str = shift;
  36.  
  37.     print LOG $str."\n";
  38. }
  39.  
  40. sub compare
  41. {
  42.     my($dir1, $dir2, @files) = @_;
  43.  
  44.     foreach my $file (@files) {
  45.         debug($file);
  46.         if ( (-f "$dir1/$file") && (-f "$dir2/$file") ) {
  47.             my $file1MD5 = md5("$dir1/$file");
  48.             my $file2MD5 = md5("$dir2/$file");
  49.             debug("$file1MD5 == $file2MD5");
  50.             if ($file1MD5 != $file2MD5) {
  51.                 print ERROR "$dir1/$file and $dir2/$file are different!\n";
  52.             }
  53.         } else {
  54.             if (!(-f "$dir1/$file")) {
  55.                 print ERROR "Missing $dir1/$file\n";
  56.             }
  57.             if (!(-f "$dir2/$file")) {
  58.                 print ERROR "Missing $dir2/$file\n";
  59.             }
  60.         }
  61.     }
  62. }
  63.  
  64. sub readfiles
  65. {
  66.     my $dir = shift;
  67.     my $files = [];
  68.  
  69.     opendir DIR, $dir || die("Couln't open dir: $dir\n");
  70.     debug("Open dir: $dir");
  71.     while (my $file = readdir(DIR)) {
  72.         if (-f "$dir/$file") {
  73.             push $files, $file;
  74.         }
  75.     }
  76.     closedir DIR;
  77.  
  78.     return $files;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement