Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Transforming File Name Characters

by rfleisch (Initiate)
on Mar 11, 2013 at 17:13 UTC ( [id://1022834]=perlquestion: print w/replies, xml ) Need Help??

rfleisch has asked for the wisdom of the Perl Monks concerning the following question:

Hello All

I need some guidance. I need to scan a folder looking at each name and folder name recursively and REMOVE special characters from those file names and folder names. I see these main tasks to do. 1. Start a directory read and retrieve an item. 2. Translate out the "special characters" to an underscore. 3. Rename the item to the new translated name. 4. If the item is a folder set it as the folder name and repeat recursively.

I need help with the translating part and the renaming part. Is renaming a folder the same as renaming a file?

Thank you - Ray Fleischmann

Replies are listed 'Best First'.
Re: Transforming File Name Characters
by choroba (Cardinal) on Mar 11, 2013 at 17:15 UTC
    Yes, renaming a directory should be the same as renaming a file.

    What do you mean by "special characters"?

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      We need to remove all / \ } { & $ # @ ~ ` pretty much anything that is NOT a letter or a number.

        You can try something along the following lines:
        fixdir('d'); sub fixdir { my $dir = shift; opendir my $DH, $dir or die "$dir: $!"; while (my $f = readdir $DH) { next if grep $_ eq $f, qw/. ../; (my $new = $f) =~ s/[^a-zA-Z0-9_.]/_/g; die "$f: $new already exists.\n" if -e "$dir/$new" and $new ne + $f; print STDERR "Renaming: $f -> $new\n"; rename "$dir/$f", "$dir/$new"; fixdir("$dir/$new") if -d "$dir/$new"; } }
        لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Transforming File Name Characters
by Kenosis (Priest) on Mar 11, 2013 at 19:26 UTC

    What happens if, upon getting ready to rename a file or folder, the new name already exists? For example:

    Old New --- --- file@{%.txt file___.txt file%{@.txt file___.txt
      Thanks I had NOT thought of that. I'm sure that the second rename will just fail and leave the file name unchanged. I'll display a message to look for it. Thank You For this "got-cha" :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1022834]
Approved by choroba
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-03-19 04:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found