Skip to content

Instantly share code, notes, and snippets.

@evandhoffman
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save evandhoffman/0a342f56c388862deb67 to your computer and use it in GitHub Desktop.

Select an option

Save evandhoffman/0a342f56c388862deb67 to your computer and use it in GitHub Desktop.
Perl script to organize a pile of MP3s into sane folders so I can put them in my car USB stick.
#!/usr/bin/perl
#
use strict;
use warnings;
#use MP3::M3U::Parser;
use MP3::Tag;
use Data::Dumper;
use File::Copy;
use File::Path;
my $basepath = '/docs/Music';
while (<>) {
my $track_file_name = shift;
#next unless ($track_file_name =~ /mp3/i);
my $mp3 = MP3::Tag->new($track_file_name);
# print "File: $track_file_name\n";
next unless defined($mp3);
$mp3->config("autoinfo","ID3v2","ID3v1","filename");
$mp3->get_tags();
my ($title, $track, $artist, $album, $comment, $year, $genre) = $mp3->autoinfo();
# $id3v2 = $mp3->{ID3v2} if exists $mp3->{ID3v2};
if ($track =~ /^[\d\/]+$/) {
($track) = split(/\//,$track);
$track = sprintf('%02d',$track) . ' - ';
} else {
$track = '';
}
if ($year =~ /^\d+$/) {
$year = '('. sprintf('%04d',$year) .') ';
} else {
$year = '';
}
$album = '(unknown)' unless ($album =~ /\w+/);
# $album =~ s/[\t\s\r\\\/]+/ /g;
my $performer = "$artist ";
if (exists $mp3 ->{ID3v2}) {
my $albumartist = $mp3->{ID3v2}->get_frame("TPE2");
$artist = $albumartist if ($albumartist =~ /\w+/);
my $art = $mp3->{ID3v2}->get_frame("TPE1");
$performer = $art if ($art =~ /\w+/);
if ($performer eq $artist) {
$performer = '';
} else {
$performer = "$performer - ";
}
}
# $artist =~ s/[\t\s\r\\\/]+/ /g;
# $performer =~ s/[\t\s\r\\\/]+/ /g;
foreach ($title, $artist, $album, $performer) {
$_ = sanitize($_);
}
my $new_path = "/$artist - $year$album/";
my $new_file = "$track$performer$title.mp3";
if (! -d "$basepath$new_path") {
mkpath("$basepath$new_path") or print STDERR "make_path failed for $basepath$new_path: $!\n";
}
move($track_file_name, "$basepath$new_path$new_file") or print STDERR "Copy failed for $track_file_name: $!\n";
print "Copied to $basepath$new_path$new_file\n";
# print Dumper $mp3;
}
exit 0;
sub sanitize {
$_ =~ s/[^a-zA-Z0-9_\-\.\']+/ /g; # Strip bad chars
$_ =~ s/([\w']+)/\u\L$1/g; # Capitalize first letter of each word
$_ =~ s/^\s+|\s+$//g; # Strip lead/trailing whitespace
return $_;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment