#!/usr/bin/perl # replace-filename-chars-windows-cant-handle.pl # # by Apollia of Astroblahhh.Com - http://astroblahhh.com/ # Completed March 20, 2011 at 1:59 PM. # # Public domain. # # This script goes through all the files in a directory you # specify in the variable $path_of_files, and renames those # files if their file names contain any characters that Windows # can't handle in file names: # # \ : * ? " < > | # # It doesn't bother filtering out / (forward slash, another # character which Windows can't handle) because I had no # files with a / in it. I don't know if Linux can even # create those. # # The filtered characters are changed into dashes. # # # Note: This script doesn't work properly in Windows XP (and # probably other versions of Windows I haven't tested this # script in). # # Perl in Windows XP (and probably in other versions of # Windows) seems to be just as powerless as Windows itself # to do anything with files that have \ : * ? " < > | in # the file name. my @files; ################ # # false|true my $run_this_script="false"; # Just a safeguard so the script # won't run unless this is # changed to true. # Yes, the quotes are required. #################### # # # Please specify the directory you want the script # to scan and rename files in. my $path_of_files="/root/testfiles/"; # # # ####################### ########### Nothing below this line needs to be changed. main(); sub main { if ($run_this_script eq "true") { chdir $path_of_files; GetFilesInDirectory($path_of_files); print "\n\nRenaming files in $path_of_files\n --------------\n"; foreach $file (@files) { if ($file eq "." or $file eq "..") { next; } $oldfilename=$file; $newfilename=$oldfilename; # \ / : * ? " < > | # Above are the characters Windows dislikes in file names. # # This script doesn't strip out / because I have no files # which contain a / in their file name. (I'm not sure Linux # can even make such files). $newfilename =~s/[\\]|[:]|[*]|[?]|["]|[<]|[>]|[|]/-/g; print $oldfilename; print " -> \n"; print $newfilename; print "\n"; if ($newfilename eq $oldfilename) { print "No change needed.\n\n"; next; } if (-e $newfilename) { warn "Can't rename '$file' to '$newfilename' since a file by that name already exists.\n\n"; } else { if (rename $file, $newfilename) { print "Rename worked!\n\n"; } else #if the rename failed... { warn "Couldn't rename '$file' to '$newfilename' for some reason.\n\n"; } } } } else { print "\nPlease change the run_this_script variable to \"true\" (in quotes) if you want to run this script.\n\n"; } } sub GetFilesInDirectory { $dir=$_[0]; opendir(DIR, $dir); @files=readdir(DIR); print "\nReading in files in $dir\n --------------\n"; foreach $file (@files) { if (-d $file) { print " DIRECTORY FOUND!!!! "; }; print $file; print " "; $size=-s $file; print $size; print "\n\n"; }; closedir(DIR); }