Reputation: 712
I'm using Banshee on Linux and I have it auto-organize my music collection in folder hierarchies. When I add a new album to my Music folder, Banshee automatically moves (and renames) the mp3s and puts them into the correct Artist folder. If there is no other file in the folder, then the folder is also deleted, but if other files are present, only the mp3s are moved and the folder remains. Because of this, I have a number of folders inside my music folder that contain no mp3s, only an image file or similar ancillary file.
How would I go about removing any folder (inside the Music folder) that does not have an mp3 file inside?
For example, suppose I have the following:
/home/user/Music/
and I add the folder "Album 1 (2010)" which has mp3s and also cover art. Banshee will pull out the mp3s and put them in the proper artist folder, say:
/home/user/Music/Artist
but then the folder
/home/user/Music/Album 1 (2010)
still exists. How can I check if this folder has an mp3 in it, and if not, delete it?
I figure the answer will be a command line one, but I'm open to any suggestion. Also, it might be good to require a confirmation... just in case.
Upvotes: 5
Views: 3293
Reputation: 58770
Based on ghostdog74's answer:
#! /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
Let's test it on the directory structure
.
./deleteme
./save2
./save2/x.MP3
./save-recursive
./save-recursive/nested
./save-recursive/nested/x.mp3
./save
./save/x.mp3
The output is:
./deleteme no mp3
Upvotes: 3
Reputation: 383
First delete not mp3 file to avid empty folder with jpg files.
find ! -iname '*.mp3' -type f -delete
if you wont delete empty folder
find -depth -type d -empty -exec rmdir {} \;
Upvotes: 2
Reputation: 342363
#! /bin/bash
shopt -s nullglob
shopt -s nocaseglob
find -depth -type d | { while read -r D;
do
case "$D" in
"$DR" ) continue;;
esac
v=$(echo "$D"/*.mp3)
case "$v" in
"" )
echo "$D no mp3, to be deleted";;
# rm -fr "$D" #uncomment to use
*)
DR=${D%/*}
;;
esac
done }
Upvotes: 0
Reputation: 281
Can't comment yet, but @ghostdog74 's find command checks the current directory for mp3s in addition to the actual subdirectories, if there are no mp3s loose in /home/user/Music, it'll remove the whole tree.
If these are completely empty directories, then rmdir *
will do the trick without any scripting needed: rmdir can't remove files or directories with files in them.
For dealing with spaces, run IFS=$(echo -en "\b\n")
either at the top of the command or in the shell first. This prevents variables from expanding into multiple arguments when the variable contains a space. If you do this in the shell, you'll probably want to do something like SAVEIFS=$IFS; IFS=...; do stuff; IFS=$SAVEIFS
so that you can get the original setting back, or just close the terminal and open a new one to get a fresh environment.
Upvotes: 1