Skip to content

Instantly share code, notes, and snippets.

@evandhoffman
Created June 16, 2012 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evandhoffman/2942231 to your computer and use it in GitHub Desktop.
Save evandhoffman/2942231 to your computer and use it in GitHub Desktop.
Reorganize MP3s according to id3 tag info
#!/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/mp3-for-car';
while (<>) {
my $track_file_name = shift;
#next unless ($track_file_name =~ /mp3/i);
my $mp3 = MP3::Tag->new($track_file_name);
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;
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";
}
copy($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;
@evandhoffman
Copy link
Author

I wrote this to organize all my mp3s into a 2-level directory structure to make it easy to find the album I want on my car's mp3 player. It only shows folder name, so having the artist & album in the folder name is important, & nested folders suck.

Usage:

find /docs/Music/ -type f -iname *.mp3 -print0 | xargs -0 perl ~/copy-mp3.pl

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment