Tuesday, April 22, 2014

Linux removing all directories of a certain name from a directory tree

Ok, so it's actually a Unix system.

I had to removed all directories of a certain name from a directory tree. No biggie, just using find here, along with du to tell me how big these bad things were on the file system:

find . -name "[directory name] -exec du --si {} \;"

Note that du -k gave it in kilobytes, and -m gave it in megabytes, and there is no -g option. However --si just picks the best units to show for each line output.

My thought was that I could use -exec rm -r {}\; with this find statment to delete the directories. However, the non grata directories appeared at different levels, sometimes within each other. This listing gave the top directories first, which meant after I had deleted the top directory find might still return the lower directory if the transfer of lines to -exec is done after find is completed. The solution was to use the argument to reverse the lower and higher level results:

find . -d -name "[directory name] -exec rm -r {} \;"

The downside to this is I was getting pestered my messages that said "find: warning: the -d option is deprecated; please use -depth instead, because the latter is a POSIX-compliant feature.". I didn't have time to figure out if -depth really is a drop-in replacement for -d.