filename_cmp_del.pl 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 16 June 2014
  5. # Website: https://github.com/trizen
  6. # Delete files from [del dir] which does NOT exists in [cmp dir]
  7. # NOTE: Only the base names are compared, without their extensions!
  8. use 5.014;
  9. use strict;
  10. use autodie;
  11. use warnings;
  12. use Getopt::Std qw(getopts);
  13. use File::Spec::Functions qw(catfile);
  14. sub usage {
  15. my ($code) = @_;
  16. print <<"EOT";
  17. usage: $0 [options] [cmp dir] [del dir]
  18. options:
  19. -d : delete the files
  20. -h : print this message
  21. example:
  22. $0 -d /my/cmp_dir /my/del_dir
  23. EOT
  24. exit $code;
  25. }
  26. # Options
  27. getopts('dh', \my %opt);
  28. $opt{h} and usage(0);
  29. # Dirs
  30. @ARGV == 2 or usage(2);
  31. my $cmp_dir = shift;
  32. my $del_dir = shift;
  33. my $rem_suffix = qr/\.\w{1,5}\z/;
  34. # Read the [cmp dir] and store the filenames in %cmp
  35. my %cmp;
  36. opendir(my $cmp_h, $cmp_dir);
  37. while (defined(my $file = readdir($cmp_h))) {
  38. my $abs_path = catfile($cmp_dir, $file);
  39. if (-f $abs_path) {
  40. undef $cmp{$file =~ s/$rem_suffix//r};
  41. }
  42. }
  43. closedir($cmp_h);
  44. # Delete each file which doesn't exists in [cmp dir]
  45. opendir(my $del_h, $del_dir);
  46. while (defined(my $file = readdir($del_h))) {
  47. my $abs_path = catfile($del_dir, $file);
  48. if (-f $abs_path) {
  49. my $name = $file =~ s/$rem_suffix//r;
  50. if (not exists $cmp{$name}) {
  51. say $abs_path;
  52. unlink $abs_path if $opt{d};
  53. }
  54. }
  55. }
  56. closedir($del_h);