msgbartop
Just another WordPress site
msgbarbottom

16 Jun 09 Renaming Files Using Perl

I finally got around to writing a script to rename all my music files to the same convention. That being either <track>-<song>.mp3 or <song>.mp3 with no spaces (I prefer underscores instead) and all lowercase. I know, it looks so simple! But the problem is all those occasions where you have something like <track>_-_<SONG>_-_(<remix by>).mp3 which just looks horrible! What this script does could be done in a lot less lines than I have here, but I thought it might be a good way for someone who is unsure of regular expressions to get a grasp on the topic.

So heres the script:

#!/usr/bin/perl -w
use strict;

# Open 'find' process to list files recursively with paths
open(FIND, "find |");
while(<FIND>) {
 # remove leading / trailing whitespace
 chomp; 

 # Don't rename ourself
 next if $_ eq $0;       

 # create temp file (windows wont allow to rename in place from uppercase to lowercase)
 my $name = $_;
 my $tmp = $_.'~';
 rename($name, $tmp);

 # make lowercase
 $name = lc($name);
 rename($tmp, $name);

 my $newname = $name;
 # remove apostrophes
 $newname =~ s/[']//g;
 # remove round brackets and replace with hyphens
 $newname =~ s/[()]/-/g;
 # remove spaces and replace with underscores
 $newname =~ s/ /_/g;
 # remove where in sequence there is underscore, hyphen, underscore and replace with a hyphen
 $newname =~ s/_-/-/g;
 $newname =~ s/-_/-/g;
 # where there are one or more digits followed by an underscore change the underscore to a hyphen
 $newname =~ s/(d+)_/$1-/g;
 # remove all ampersands and replace them with '_and_'
 $newname =~ s/&/_and_/g;
 # remove underscores where there are 2 or more, and replace with a single underscore
 $newname =~ s/_{2,}/_/g;

 # write out the changes
 rename($name,$newname);

}
close(FIND);