比较两个目录文件是否相同

类别:软件工程 点击:0 评论:0 推荐:

有时候我们需要比较vss里两个目录下的source是否一致,而但从日期根本看不出什么来,所以需要逐一的比较,项目很大时,这项工作比较恼人。所以我做了一个工具,它能调查出来哪些文件内容相同,哪些不同,哪些仅在一个目录存在。
compDir.pl
#!/usr/bin/perl

die "parameter is not enough.\n"
 if @ARGV < 2;

$now = localtime time;
print "compDir begin at $now\n";

sub compFile {
 my $file1 = $_[0];
 my $file2 = $_[1];

 open SRC, "$file1"
  or die "cannot open file '$file1': $!\n";
 open DEST, "$file2"
  or die "cannot open file '$file2': $!\n";

 my @data1 = <SRC>;
 my @data2 = <DEST>;

 print "<$file1> and <$file2> are different files.\n" and return
  if @data1 != @data2;

 while (1) {
  my $d1 = shift @data1;
  my $d2 = shift @data2;
  last if !defined $d1;
  print "<$file1> and <$file2> are different files.\n" and return
   if $d1 ne $d2;
 }
 if (@data1 != 0) {
  print "<$file1> and <$file2> are different files.\n" and return;
 }

 #print "<$file1> and <$file2> are same files.\n"
 close SRC;
 close DEST;
}

sub get_file {
 my $dir = $_[0];
 shift @_;
 chdir $dir or die "cannot chdir to '$dir': $!\n";

 my @files = <*>;
 foreach $file (@files) {
  if (-d "$dir\\$file") {
   @_ = &get_file("$dir\\$file", @_);
  } else {
   push @_, "$dir\\$file";
  }
 }
 @_;
}


sub get_short_name {
 $string = $_[0];
 $mode = $_[1];

 $mode =~ s/\\/\\\\/;
 $string =~ s/^$mode\\//;

 $string;
}

@name1 = &get_file($ARGV[0], @name1);
@name2 = &get_file($ARGV[1], @name2);

%nameHash1;
foreach (@name1) {
 my $short_name = &get_short_name($_, $ARGV[0]);
 $nameHash1{$short_name} = $_;
}

%nameHash2;
foreach (@name2) {
 my $short_name = &get_short_name($_, $ARGV[1]);
 $nameHash2{$short_name} = $_;
}

foreach (@name1) {
 my $short_name = &get_short_name($_, $ARGV[0]);
 
 if (exists $nameHash2{$short_name}) {
  &compFile($_, $nameHash2{$short_name});
 } else {
  print "$_ exist only! \n";
 }
}

foreach (@name2) {
 my $short_name = &get_short_name($_, $ARGV[1]);
 
 if (exists $nameHash1{$short_name}) {
  # &compFile($_, $nameHash2{$short_name});
 } else {
  print "$_ exist only! \n";
 }
}

$now = localtime time;
print "compDir end at $now\n";

运行结果:
C:\>perl compDir.pl d:\plsql d:\plsql2
compDir begin at Thu Nov 11 17:42:32 2004
<d:\plsql\aaa.txt> and <d:\plsql2\aaa.txt> are different files.
d:\plsql\aaaaa\twoSql.sql exist only!
d:\plsql\bbbb.txt exist only!
d:\plsql2\aaaaa\bbb\getSource.sql exist only!
compDir end at Thu Nov 11 17:42:33 2004

本文地址:http://com.8s8s.com/it/it34093.htm