Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

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.

share|improve this answer
    
Stephane, -mtime -180 does not indicate 180 days and older. It is rather from now to 180 days if I'm not mistaken. –  val0x00ff Apr 17 at 20:37
    
Thanks Stephane - but your answer also doesn't address the most critical component which is that I only want to remove directories that contain ONLY old (180+ days) files –  pk7 Apr 17 at 21:34
    
@val0x00ff It removes the directories that do not contain files younger than 180 days. –  Stéphane Chazelas Apr 17 at 21:58
1  
@pk7, if the directories contain only 180+ days (or if the directories are empty), then find will output nothing, then grep will return false, then echo rm will be executed. –  Stéphane Chazelas Apr 17 at 22:00

One of the approaches is:

while read -r line; do rm -rf "${line%%/*}"; done < <(find . -type f -mtime +180 -printf "%P\n")

Pipe the into read and execute a command accordingly.

share|improve this answer
1  
Thanks val0x00ff- but your answer doesn't address the most critical component which is that I only want to remove directories that contain ONLY old (180+ days) files –  pk7 Apr 17 at 21:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.