Rename files using perl.


/ Published in: Perl
Save to your folder(s)

Renames files in a directory. If no directory is specified, the current directory is used.


Copy this code and paste it in your HTML
  1. #! /usr/bin/perl
  2.  
  3. ##
  4. ## Renames files in a directory. If no directory is
  5. ## specified, the current directory is used.
  6. ##
  7.  
  8. use strict;
  9. use warnings;
  10. use File::Copy;
  11. use Getopt::Long;
  12.  
  13. my $directory = "";
  14. my $from = "";
  15. my $to = "";
  16.  
  17. my $getOptionsResult=GetOptions(
  18. "--directory=s" => \$directory,
  19. "--from=s" => \$from,
  20. "--to=s" => \$to,
  21. );
  22.  
  23.  
  24. &displayUsageAndDie if $to eq "";
  25. &displayUsageAndDie if $from eq "";
  26. $directory = "." if $directory eq "";
  27.  
  28.  
  29. opendir(my $dh,$directory) or die "Unable to open $directory: $!";
  30. while(readdir($dh))
  31. {
  32. &renameFiles($_,$to) if m/$from/;
  33. }
  34. close($dh);
  35.  
  36.  
  37. sub renameFiles()
  38. {
  39. my $f = $_;
  40. chomp $f;
  41. (my $t = $f) =~ s/$from/$to/g;
  42. printf("renaming '%s' to '%s'\n",$f,$t);
  43. move($f, $t) or die(qq{failed to move $f -> $t});
  44. }
  45.  
  46.  
  47. sub displayUsageAndDie()
  48. {
  49. Renames files in a directory. If no directory is
  50. specified, the current directory is used.
  51.  
  52. usage:
  53. rename --from from --to to [--directory directory]
  54.  
  55. ";
  56. exit 1;
  57. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.