5

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.

2 Answers 2

6

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.

4
  • Stephane, -mtime -180 does not indicate 180 days and older. It is rather from now to 180 days if I'm not mistaken. Commented Apr 17, 2014 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 Commented Apr 17, 2014 at 21:34
  • @val0x00ff It removes the directories that do not contain files younger than 180 days. Commented Apr 17, 2014 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. Commented Apr 17, 2014 at 22:00
1

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.

1
  • 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 Commented Apr 17, 2014 at 21:39

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.