Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Transforming File Name Characters

by rfleisch (Initiate)
on Mar 11, 2013 at 17:13 UTC ( #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

Comment on Transforming File Name Characters
Re: Transforming File Name Characters
by choroba (Abbot) 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
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? | Other CB clients
Other Users?
Others musing on the Monastery: (9)
As of 2014-07-10 08:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (202 votes), past polls