Mark Rogers wrote:
Starting in a directory on my server, I need to delete all directories below it which only contain files older than a certain age.
To be clear, I don't just want to delete old files; if a directory has any new files in it then I don't want to delete the older files that might also be in there.
Background: I run dspam on a server, and it creates a directory for each mail address it scans, containing a log and a quarantine mailbox, amongst other things. I have many many directories that were created automatically for non-existent users and haven't seen any changes in months or even years, but "active" directories do have old files in them (preferences files, etc). So I want to find directories that haven't had any of their contents change in (say) 6 months, and then delete the whole directory.
A quick and dirty command line:
# create example directory tree. $ mkdir formark $ cd formark $ mkdir -p ./somedir/newonly ./somedir/newandold ./somedir/oldonly $ touch ./somedir/newonly/newish $ touch ./somedir/newandold/newish $ touch ./somedir/newandold/newish2 $ touch --date="1 year ago" ./somedir/newandold/oldish $ touch --date="1 year ago" ./somedir/newandold/oldish2 $ touch --date="1 year ago" ./somedir/oldonly/oldish3
# find the dirs with new files; we want to keep them $ find . -mindepth 1 -type f -mtime -180 | xargs -n 1 dirname | uniq | sort | tee keepers
# get all dirs, filter out the keepers $ find . -mindepth 1 -type d -exec /bin/sh -c "echo checking {}; if ! grep -q {} keepers; then echo {} >> delme; fi" ;
$ cat delme ./somedir/oldonly
# do the delete $ xargs --interactive -n 1 rm -r < delme
Or with a python script:
$ cat > delme.py <<EOM from __future__ import generators import os, time
old = time.time() - 6*30*24*60*60
def onlyolddir(dir): for f in os.listdir(dir): fullpath = os.path.join(dir,f) if os.path.getmtime(fullpath) > old: return False return True;
def dirwalk(dir): for f in os.listdir(dir): fullpath = os.path.join(dir,f) if os.path.isdir(fullpath) and not os.path.islink(fullpath): yield fullpath for x in dirwalk(fullpath): yield x
for elem in dirwalk("."): if onlyolddir(elem): print elem EOM $ python delme.py > delme
Disclaimer: Untested on complex filenames and directory structures, may set fire to your cat, make backups first, season to taste, etc etc.
-- Martijn