collect_gifs.pl 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/perl
  2. # Collect and move GIF images into a specific directory, by scanning a given a directory (and its subdirectories) for GIF images.
  3. use 5.036;
  4. use File::Find qw(find);
  5. use File::Copy qw(move);
  6. use File::Path qw(make_path);
  7. use File::Basename qw(basename);
  8. use File::Spec::Functions qw(catfile curdir rel2abs);
  9. use Getopt::Long qw(GetOptions);
  10. my $use_exiftool = 0; # true to use `exiftool` instead of `File::MimeInfo::Magic`
  11. sub is_gif ($file) {
  12. if ($use_exiftool) {
  13. my $res = `exiftool \Q$file\E`;
  14. $? == 0 or return;
  15. defined($res) or return;
  16. return ($res =~ m{^MIME\s+Type\s*:\s*image/gif}mi);
  17. }
  18. require File::MimeInfo::Magic;
  19. (File::MimeInfo::Magic::magic($file) // '') eq 'image/gif';
  20. }
  21. sub collect_gif ($file, $directory) {
  22. my $dest = catfile($directory, basename($file));
  23. if (-e $dest) {
  24. warn "File <<$dest>> already exists...\n";
  25. return;
  26. }
  27. move($file, $dest);
  28. }
  29. GetOptions('exiftool!' => \$use_exiftool,)
  30. or die "Error in command-line arguments!";
  31. my @dirs = @ARGV;
  32. @dirs || die "usage: perl $0 [directory | files]\n";
  33. my $directory = rel2abs("GIF images"); # directory where to move the files
  34. if (not -d $directory) {
  35. make_path($directory)
  36. or die "Can't create directory <<$directory>>: $!";
  37. }
  38. if (not -d $directory) {
  39. die "<<$directory>> is not a directory!";
  40. }
  41. find(
  42. {
  43. wanted => sub {
  44. if (-f $_ and is_gif($_)) {
  45. say ":: Moving file: $_";
  46. collect_gif($_, $directory);
  47. }
  48. },
  49. },
  50. @dirs
  51. );