Saturday, April 17, 2010

Perl script for renaming music files

Ok, I used one of the free ipod backup programs and it copied all of the file with native format, e.g. UBOT.m4a - great, now I have to write a perl program to read the metadata and rename the files.

Quick and dirty, but here you go:

 #!/usr/local/bin/perl
use MP4::Info;
use MP3::Info;

MP3s();
MP4s();


sub stripUnwanted
{
my $filename=shift;
    $filename =~ tr{\\\/}{-};
    $filename =~ tr{*?}{X};
    $filename =~ tr{“><[]|:;,’=\"}{_};
return $filename;
}

sub MP3s {
@files = <*.mp3>;

    foreach $file (@files) {  
        my $tag  = get_mp3tag($file);
        $artist = $tag->{ARTIST};
        $title = $tag->{TITLE};
  
        $artist = stripUnwanted($artist);
        $title = stripUnwanted($title);
  
        print "Artist: $artist - Title: $title\n";
        rename ($file, "$artist-$title.mp3");
    }  
}

sub MP4s {
@files = <*.m4*>;
  
    foreach $file (@files) {  
        my $mp4 = new MP4::Info $file;
        $artist = $mp4->artist;
        $title = $mp4->title;
  
        $artist = stripUnwanted($artist);
        $title = stripUnwanted($title);
  
        print "$artist - $title\n";
  
        rename ($file, "$artist-$title.m4a");
  
    }
}

No comments: