Eric Eric - 2 years ago 88
Linux Question

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.

Answer Source

I would do it as follows in Bash:


# Set field separator to dash

# 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"

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 length 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download