Linux – Find directories with all files inside older than X

directory-listingfindlinux

Is it possible on linux to find directories where all contained files and directories (and sub-directories' files etc.) are older than a given age? In other words, if a directory has one or more files within that have a modification date more recent than a given threshold, that directory should not be listed. If all of the files and folders below that directory are older than the given threshold, then that directory should be listed.

The use case is that my home directory is full of hidden directories, and I'm sure that many of them are left overs from previous installations, and software that I haven't used in years. I'd like to be able to find these directories, so I can easily decide whether to cull them.

Best Answer

It's probably possible to do this without creating files using process substitution or something, but here's a quick-and-dirty solution:

find . -type f -mtime +30 -printf '%h\n' | sort | uniq > old.txt
find . -type f -mtime -30 -printf '%h\n' | sort | uniq > new.txt
grep -vf new.txt old.txt

The first command outputs the path of every file modified more than 30 days ago (in find's -printf -- at least with the GNU find on my system -- %h prints the whole path except for the actual filename), then sorts those and gets rid of any duplicates, and puts the whole thing into a file called old.txt.

The second command does the same but with every file modified less than 30 days ago, and puts them into another file, new.txt.

The grep line prints every line from old.txt that doesn't appear in new.txt -- so it will give you a list of directories that contain only files that were last modified more than 30 days ago.

This is all using the GNU versions of the utilities. I don't know if the syntax matches up on the BSD versions, etc.