#!/usr/bin/perl -w
# #############################################################################
#
# Author: Vulcho Nedelchev <kumcho@vulcho.com>
#
# Description:
# This tool was made to convert filenames from URL
# encoded like "this%20one.fext" to this_one.fext"
# in order to be more comprehensive. By the given
# params it will make a test to specify if this is
# a DIRECTORY or a FILENAME and will fix all filenames
# in the directory if it is a directory or a single
# filename. It is useful if a wget or a similiar tool
# is used to download files from the internet.
# It is not perfect but I have no problems with it.
#
# ENJOY!
#
# url: http://www.vulcho.com/perl/cn.html
#
# Note: current version is for unix/linux platform only :)
#
# #############################################################################
use strict;
my ( $file_name, $path );
&usage unless scalar @ARGV != 1;
$path = $ARGV[1];
print "is readable - ok...\n" if -r $path;
print "is writable - ok...\n" if -w $path;
if ( -f $path ) {
convert($path);
exit;
}
if ( -d $path ) {
chomp( my @list = `ls $path` );
for ( grep( "*", @list ) ) {
convert( $path . $_ );
}
exit;
}
print "\nError processing: $path\n$!", "\n\n";
# ##############################################################################
sub convert {
my $path = shift;
return unless -f $path;
return unless $path =~ /\.mp3$/i;
my @all = split ( '/', $path );
$file_name = pop (@all);
my $dir = join ( '/', @all );
# edit Filename
$file_name =~ s/\.mp3$//ig;
$file_name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$file_name =~ s/\s+/_/g;
$file_name =~ s/_-_/-/g;
$file_name =~ s/\.//g;
$file_name =~ s/_(\(|\))/$1/g;
$file_name =~ s/(\(|\))_/$1/g;
$file_name =~ s/\`|\"|\'/_/g;
$file_name =~ s/\_+/_/g;
$file_name =~ s/\-+/_/g;
$file_name =~ s/^_//;
my $new_file_name = $dir ? $dir . '/' . $file_name . ".mp3" : $file_name . ".mp3";
print "$path -> $new_file_name\n";
rename($path, $new_file_name) or die "Cannot rename file: $!";
}
sub usage {
print "\n\tusage: $0 {directory|filename}\n\n";
exit;
}