Removing ASCII codes from filenames

Jun 05, 2011 12:42


Originally published at Dom's Blog. You can comment here or there.

Sometimes when files are downloaded by automated download scripts, or just saved directly from a website, the filenames contain ASCII characters encoded with the percentage symbol, e.g.:

This%20filename%20contains%20spaces.html

Whilst this is considered bad practice, it is sometimes unavoidable (for example when downloading content which is saved dependant on the title of a page, not the filename of the source), so I wrote this little script to rename each of the files in a directory:

#!/opt/local/bin/perl -w
# A script to replace the ASCII codes in filenames with their actual characters
# Note: no checking is done
if ($#ARGV < 0 ) {
print "usage: substitute_ascii.pl \n";
exit;
}

# Process each argument in turn, saving the original name
# then replacing each ASCII code with its actual character
foreach $value (@ARGV) {
$original = $value;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
if ( rename("$original", "$value") ) { print "$original -\> $value\n"; } else { print "Rename operation failed\n"; }
}

shell

Previous post Next post
Up