Ubuntu – Reorder Files inside Folder

11.04filesscripts

I have about 30K songs in mp3. I already organized/tagged them with Musicbrainz Picard. But Picard made an excess of folders and subfolders inside each other because of the tags.

What I need now is a script to read each subfolder and move all the mp3 files inside the subfolder's folders to the main subfolder. For example:

 Music -  
   Offspring -
      Album 1 - 20 songs
      Album 2 - 30 songs
      Album 3 - 5 Songs
         Folder 1 - 2 Songs
         Folder 2 - 3 Songs
   Journey -
      Song Pack 1 - 2 Songs
           Packy 1 - 15 Songs
           Packy 2 - 20 Songs
           Packy 3 - 7 Songs
      Album 2 - 20 songs
      Whatever 3 - 10 Songs

After running the script they would be like this:

Music -    
   Offspring - All Songs inside THIS folder. Not inside subfolders of Offspring.  
   Journey - All Songs inside THIS folder. Not inside subfolders of Journey.   

And so on..

So all the music for each subfolder of each music group should not have any more subfolders and all songs inside their respective sub-subfolders should be moved to the main sub-folder of the music group.

So when I check Music and I see the Bee Gees then I KNOW that all the songs are right there and not inside some subfolder of Bee Gees.

NOTE – In some cases there are more than 20 recursive sub-folders. An example is: Music/Lady Gaga/1/Album/Lady Gaga/2/2/2/1/1/1/1/3/3Album 2/Lady Gaga/1/1/1/SONG.mp3. In this case I want these inside Music/Lady Gaga and to eliminate the rest of the folders.

Best Answer

I suggest the following (tested, but without warranty) script, to be run from the master directory, under which all artists directories live:

#!/bin/bash

for f in *; do
  find "$f" -mindepth 2 -type f -exec mv --backup=numbered -t "$f" {} +
done

for f in *; do
  find "$f" -mindepth 1 -type d
done |
  sort -r |
  while read d; do
    rmdir "$d"
  done

It also take care of duplicates and empty sub-directories removal.