Find directories without music files

filesfind

My ~/Music/ directory is actually full of "empty" directories I want to clean. I say "empty" because this directories actually contain files, some contain old cover image files or Thumbs.db files.

I want to recursively delete all of these directories that don't contain any music files inside or other directories inside.

For example ~/Music/Audioslave/ contains a lot of directories with album names and no music files, but I don't want to delete it because inside there are the music files. I want though to delete ~/Music/Audioslave/oldalbum/ if the oldalbum directory doesn't have nor music files nor other directories inside.

Best Answer

I found this example on SO, titled: Terminal - Delete All Folders Not Conatining .mp3 Files.

#! /bin/bash

find -depth -type d | while read -r D
 do
 v=$(find "$D" -iname '*.mp3')
 case "$v" in
 ""  )
    echo "$D no mp3"
    # rm -fr "$D" #uncomment to use
 ;;
 esac
done

Example

Sample data.

.
|-- 1
|   |-- 1.mp3
|   `-- 1.txt
|-- 2
|   `-- 2.mp3
|-- 3
|   `-- 3.txt
|-- 4
|   `-- 4.txt
|-- 5
|   `-- 5.mp3
|-- 6
|   `-- 61
|       `-- 61.mp3
|-- 7
|   `-- 71
|       `-- 71.txt
`-- deletenomp3.bash

Sample run

If I were to run it it would delete the following:

$ ./deletenomp3.bash 
./7 no mp3
./7/71 no mp3
./4 no mp3
./3 no mp3

Other file types

You can simply extend this by adding more -name arguments to the 2nd find command in the script. Example, to add .wav files:

 v=$(find "$D" -iname '*.mp3' -o -iname '*.wav');

That says *.mp3 OR *.wav. To add more or others:

 v=$(find "$D" -iname '*.mp3' -o -iname '*.flac' -o -iname '*.m4a');

I'm sure this block could be condensed if you had a lot more file types using alternative switching to find.

Related Question