copy-if-different.pl 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/local/bin/perl
  2. use strict;
  3. use Fcntl;
  4. # copy-if-different.pl
  5. # Copy to the destination if the source is not the same as it.
  6. my @filelist;
  7. foreach my $arg (@ARGV) {
  8. $arg =~ s|\\|/|g; # compensate for bug/feature in cygwin glob...
  9. foreach (glob $arg)
  10. {
  11. push @filelist, $_;
  12. }
  13. }
  14. my $fnum = @filelist;
  15. if ($fnum <= 1)
  16. {
  17. die "Need at least two filenames";
  18. }
  19. my $dest = pop @filelist;
  20. if ($fnum > 2 && ! -d $dest)
  21. {
  22. die "Destination must be a directory";
  23. }
  24. foreach (@filelist)
  25. {
  26. my $dfile;
  27. if (-d $dest)
  28. {
  29. $dfile = $_;
  30. $dfile =~ s|^.*[/\\]([^/\\]*)$|$1|;
  31. $dfile = "$dest/$dfile";
  32. }
  33. else
  34. {
  35. $dfile = $dest;
  36. }
  37. my $buf;
  38. if (-f $dfile)
  39. {
  40. sysopen(IN, $_, O_RDONLY|O_BINARY) || die "Can't Open $_";
  41. sysopen(OUT, $dfile, O_RDONLY|O_BINARY)
  42. || die "Can't Open $dfile";
  43. while (sysread IN, $buf, 10240)
  44. {
  45. my $b2;
  46. goto copy if !sysread(OUT, $b2, 10240) || $buf ne $b2;
  47. }
  48. goto copy if sysread(OUT, $buf, 1);
  49. close(IN);
  50. close(OUT);
  51. print "NOT copying: $_ to $dfile\n";
  52. next;
  53. }
  54. copy:
  55. sysopen(IN, $_, O_RDONLY|O_BINARY) || die "Can't Open $_";
  56. sysopen(OUT, $dfile, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY)
  57. || die "Can't Open $dfile";
  58. while (sysread IN, $buf, 10240)
  59. {
  60. syswrite(OUT, $buf, length($buf));
  61. }
  62. close(IN);
  63. close(OUT);
  64. print "Copying: $_ to $dfile\n";
  65. }