Deleting directories
Larry Wall
lwall at jpl-devvax.JPL.NASA.GOV
Wed Jul 11 03:44:15 AEST 1990
In article <37481 at ucbvax.BERKELEY.EDU> ashish at janus.Berkeley.EDU.UUCP (Ashish Mukharji) writes:
: Recently, I had to remove all of a user's files older than a
: certain date. That was easily accomplished with find(1), but deleting the
: resulting (empty) directory structure presents a greater problem. The user's
: home directory is the root of a large, mostly empty directory tree. I want
: to delete all directories that do not contain any regular files - find starts
: with . and works its way down (inorder). What I need is a way to do a
: postorder traversal of the directory structure. Is there a simple way, short
: of writing a C routine?
With regard to getting the directories in the right order, some find programs
have a -depth switch to do this. Otherwise, pipe the output through sort -r.
Then you have to wrap something around to do the rmdir:
If there aren't too many:
rmdir `find . -type d -print | sort -r`
If you have xargs:
find . -type d -print | sort -r | xargs rmdir
If you have Perl:
find . -type d -print | sort -r | perl -ne 'chop; rmdir;'
Using sh:
find . -type d -print | sort -r | while read dir; do rmdir $dir; done
Using sed:
find . -type d -print | sort -r | sed 's/^/rmdir /' | sh
With all but one of these, you'll have to ignore the error messages on
directories that can't be removed. (Where ignoring may consist of >&/dev/null
or 2>/dev/null, depending on your culture (or lack thereof :-).)
The perl solution will be most efficient if you have the rmdir system call.
Otherwise the xargs solution will probably be best.
Larry Wall
lwall at jpl-devvax.jpl.nasa.gov
More information about the Comp.unix.questions
mailing list