copy-if-different.pl 1.4 KB

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