http://www.perlmonks.org?node_id=986295


in reply to Create folder hierarchy based on MP3 tags

Handy script! I added some tag checking/customization:
#!/usr/bin/perl use strict; use warnings; # Create folder hierarchy based on MP3 tags. # Based on: http://www.perlmonks.org/?node_id=985820 # To get mp3 files from directories # find /path/to/mp3_dirs/ -iname '*.mp3' -exec cp "{}" . \; use MP3::Tag; use File::Copy::Recursive qw(fmove); my $Debug = 1; # 1 - don't move files just print the new path foreach my $file (<*.mp3>) { my $mp3 = MP3::Tag->new($file); my ( $title, $track, $artist, $album ) = ( $mp3->autoinfo() )[ 0, +1, 2, 3 ]; $mp3->close(); # Check/customize tags $track = $track =~ /^([0-9]+)/ ? sprintf "%02d", $1 : undef; $title = $title eq '' ? 'uknown_title' : $title; $artist = $artist eq '' ? 'uknown_artist' : $artist; $album = $album eq '' ? 'uknown_album' : $album; s/[\\\/:*?"<>|]//g for $artist, $album; # Set the new path my $path = defined $track ? "$artist/$album/$track $title.mp3" : "$artist/$album/$title.mp3"; if ($Debug) { print "$path\n"; } else { fmove( $file, $path ) or warn "Can't fmove '$file': $!"; } }
Update: Replaced path setting if structure with the ternary operator.

Have a nice day, j

Replies are listed 'Best First'.
Re^2: Create folder hierarchy based on MP3 tags
by hbm (Hermit) on Aug 08, 2012 at 15:22 UTC

    Ternary is nice, but I'd check the tags this way, in case any is just whitespace:

    $title = 'unknown_title' if $title !~ /\S/; $artist = 'unknown_artist' if $artist !~ /\S/; $album = 'unknown_album' if $album !~ /\S/;
Re^2: Create folder hierarchy based on MP3 tags
by thmsdrew (Scribe) on Aug 08, 2012 at 15:13 UTC

    Awesome, thanks for adding! Also, that debug thing you did there is pretty neat. I've never thought to do something like that.