Remove Linux directories containing ONLY old files

filesrecursive

We have numerous directories that each contain 2 files, one of which is a hidden file. We want to remove all those directories and their contents that contain ONLY files that have a modification date older than 180 days. So, for example, if we have the following:

Dir1   Jan 1 2000
     File1A   Jan 1 2000
     File1B   Jan 1 2000
Dir2   Jan 1 2000
     File2A   Jan 1 2014
     File2B   Jan 1 2014
Dir3   Jan 1 2000
     File3A   Jan 1 2014
     File3B   Jan 1 2000

I need a Linux command that will remove only Dir1 and all of its contents including the hidden file. Dir2 and Dir 3 would remain untouched because each contain at least one file that is newer than 180 days ago.

I've played around with listing those directories that contain a newer file but I couldn't find an "inverse" command that would then remove all the "other" directories.

Best Answer

With GNU tools:

for d in Dir*; do
  find "$d" -mindepth 1 -mtime -180 -print -quit | grep -q . ||
    echo rm -rf "$d"
done

Remove the echo when satisfied. Remove the -q to find out why a directory is not being removed.

Related Question