Skip to content
Advertisement

Move mp3 files from one directory to separate directories by artist, album, song name

I have a backup of all my mp3s files in one folder.

Would there be a bash command to automatically move all files in their own band-album title directories that would be created on the fly?

As you can see in the image, first words before dash are artist names, then comes the album title, then comes the name of the song.

enter image description here

Example: Artist or band – album title – name of song.mp3.

So in the end, files would be in the following hierarchy.

Artist or band1/    
        album title1/
                name of song.mp3
        album title2/
                name of song.mp3    

Artist or band2/
        album title1/
                name of song.mp3

and so forth.

Advertisement

Answer

I would do it as follows in Bash:

#!/bin/bash

# Set field separator to dash
IFS=-

# Loop over mp3 files
for song in *.mp3; do

    # Read long name into dash separated array
    read -a songinfo <<< "$song"

    # Remove trailing space from band name
    band=${songinfo[0]% }

    # Remove trailing and leading space from album name
    album=${songinfo[1]% }
    album=${album# }

    # Remove leading space from song title
    title=${songinfo[2]# }

    # Make band/album directory, don't complain if they exist already
    mkdir --parents "$band/$album"

    # Move and rename song
    mv "$song" "$band/$album/$title"
done

This changes the IFS variable, but since this will be running in a child process, I didn’t bother resetting it to its original value.

It’s a bit lengthy due to parameter expansions to remove spaces, and it of course breaks if there is a dash in places other than between band/album/song names. For a Bash solution that also works with dashes in other places, see mklement0’s answer.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement