Advertisement
Guest User

Untitled

a guest
Jun 28th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.75 KB | None | 0 0
  1. #!/opt/local/bin/perl
  2.  
  3. # rename files and dirs
  4. #
  5. # try to get special chars in filenames right via Text::Unidecode()
  6. # i.e. replace them with "_"
  7. #
  8. # also change the filenames to lowercase
  9. #
  10. # bugs:
  11. # this script does not work with (e.g.) "!" in filenames
  12. # there are probably more chars that cause problems
  13. # but you will notice when it comes to that
  14.  
  15. use strict;
  16. use File::Basename;
  17. use Data::Dumper;
  18. use Text::Unidecode;
  19.  
  20. my $regex = "[^a-z0-9\-\_\.]";
  21. my $dir_counter = 0;
  22. my $file_counter = 0;
  23.  
  24. my @dirs = find("d");
  25. shift(@dirs);
  26. foreach(@dirs) {
  27.     if(re_name($_)) {
  28.         $file_counter++;
  29.     }
  30. }
  31.  
  32. my @files = find("f");
  33. foreach(@files) {
  34.     if(re_name($_)) {
  35.         $file_counter++;
  36.     }
  37. }
  38.  
  39. print "\n===>>> renamed $dir_counter dirs \n";
  40. print "===>>> renamed $file_counter files \n";
  41.  
  42. sub re_name {
  43.     chomp(my $str = shift);
  44.  
  45.     my $basename = basename($str);
  46.  
  47.     if($basename) {
  48.         if(re_name_req($basename)) {
  49.             my $new_name = get_name($basename);
  50.             print "===>>> old name: ".$basename."\n";
  51.             print "===>>> new name: ".$new_name."\n";
  52.             if(rename $str, dirname($str)."/".$new_name) { return 1; }
  53.         }
  54.     }
  55.  
  56.     return 0;
  57. }
  58.  
  59. sub re_name_req {
  60.     chomp(my $str = shift);
  61.  
  62.     if(!$str) { return 0; }
  63.  
  64.     if($str =~ m/($regex)+/g) {
  65.         return 1;
  66.     }
  67.     else {
  68.         return 0;
  69.     }
  70. }
  71.  
  72. sub get_name {
  73.     chomp(my $str = shift);
  74.  
  75.     $str = lc(unidecode(lc($str)));
  76.     $str =~ s/$regex/\_/ig;
  77.     $str =~ s/\!/_/ig;
  78.  
  79.     return $str;
  80. }
  81.  
  82. sub find {
  83.     my $type = shift;
  84.  
  85.     if(-d $ARGV[0]) {
  86.         return `find $ARGV[0] -type $type`;
  87.     }
  88.     else {
  89.         die "first parameter must be a directory \n";
  90.     }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement