Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/opt/local/bin/perl
- # rename files and dirs
- #
- # try to get special chars in filenames right via Text::Unidecode()
- # i.e. replace them with "_"
- #
- # also change the filenames to lowercase
- #
- # bugs:
- # this script does not work with (e.g.) "!" in filenames
- # there are probably more chars that cause problems
- # but you will notice when it comes to that
- use strict;
- use File::Basename;
- use Data::Dumper;
- use Text::Unidecode;
- my $regex = "[^a-z0-9\-\_\.]";
- my $dir_counter = 0;
- my $file_counter = 0;
- my @dirs = find("d");
- shift(@dirs);
- foreach(@dirs) {
- if(re_name($_)) {
- $file_counter++;
- }
- }
- my @files = find("f");
- foreach(@files) {
- if(re_name($_)) {
- $file_counter++;
- }
- }
- print "\n===>>> renamed $dir_counter dirs \n";
- print "===>>> renamed $file_counter files \n";
- sub re_name {
- chomp(my $str = shift);
- my $basename = basename($str);
- if($basename) {
- if(re_name_req($basename)) {
- my $new_name = get_name($basename);
- print "===>>> old name: ".$basename."\n";
- print "===>>> new name: ".$new_name."\n";
- if(rename $str, dirname($str)."/".$new_name) { return 1; }
- }
- }
- return 0;
- }
- sub re_name_req {
- chomp(my $str = shift);
- if(!$str) { return 0; }
- if($str =~ m/($regex)+/g) {
- return 1;
- }
- else {
- return 0;
- }
- }
- sub get_name {
- chomp(my $str = shift);
- $str = lc(unidecode(lc($str)));
- $str =~ s/$regex/\_/ig;
- $str =~ s/\!/_/ig;
- return $str;
- }
- sub find {
- my $type = shift;
- if(-d $ARGV[0]) {
- return `find $ARGV[0] -type $type`;
- }
- else {
- die "first parameter must be a directory \n";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement