Find and delete empty directories
- 0
- Add a Comment
I had iTunes “help” me organize my musik for a while. Now I’ve abandoned it for this reason, among others (e.g. it’s terribly slow and playback stutters).
I’ve used http://musicbrainz.org/ products to clean up the mess, but only to be left with a bunch of empty directories (thanks again, iTunes). I wrote up this ruby script to take care of them for me:
class String
# Sets the proper singular or plural suffix of a word.
# Self should be the singular form of the word.
def suffix(n)
return self if n == 1
case self
when /n$/
"#{self}s"
when /y$/
"#{self[0...-1]}ies"
else
self # don't know what to do about this ending
end
end
end
def delete_empty_directories(root_directory)
iterations = deleted_total = 0
loop do # a directory containing an directory will become empty when the subdir is removed
iterations += 1
deleted = 0
Dir[File.join(root_directory,'**','*')].each do |e|
next unless File.directory?(e)
next unless (Dir.entries(e)-['.','..']).empty?
Dir.delete(e) # will fail if e is not, in fact, an empty dir
deleted += 1
end
break if deleted.zero?
deleted_total += deleted
puts "Iteration #{iterations}: deleted #{deleted} empty #{'directory'.suffix(deleted)}"
end
puts "Deleted #{deleted_total} empty #{'directory'.suffix(deleted_total)} "+
"under #{root_directory} in #{iterations} #{'iteration'.suffix(iterations)}"
end
delete_empty_directories(File.join('d:','Media','Musik'))
The code will enter my music directory and find all entries recursively (Dir[File.join(root_directory,’**’,'*’)]). Among those it finds empty directories i.e. directories which contain only the self- and parent-references (. and .. resp.) and deletes them.
This process is repeated until there are no more directories that can be deleted. The reason for repeating is that an empty sub directory may be the only thing keeping its parent from being empty, but the child must be removed before this becomes evident.
The code also contains a simple mechanism for properly suffixing words in singular and plural form. I got really tired of all those programs just writing something like Finished processing %n element(s) when you can easily find the correct suffix of element(s) so that it corresponds to %n. Maybe this can serve as inspiration!
