1

Is there is any solution to delete the files based on comparing their modified date with the most recently modified file? The older files need to be deleted with respect to most recent file.

For example, if the last modified date is 09-10-2017, it means the files that are 10 days older need to be deleted. Same if the modified date is changed; the files to be deleted should change accordingly.

  • 1
    what if Last modified date is 01-03-2017 ? – RomanPerekhrest Oct 9 '17 at 10:06
  • You want to delete the files that are more than 10 days older than the most recently modified file? – Stéphane Chazelas Oct 9 '17 at 10:09
  • yes, It needs to deleted accordingly with latest file – Vignesh Vignasivakara Oct 9 '17 at 10:58
3

With GNU tools:

find . -type f -printf '%T@:%p\0' |
  sort -rzn |
  awk -v RS='\0' -v ORS='\0' -F: -v d=10 '
    NR == 1 {t = $1 - 86400 * d}
    $1 < t, 0 {sub(/[^:]*:/, ""); print}' |
  xargs -r0 echo rm

(remove the echo when happy).

We're getting find to print 123456.123:./path/to/file<NUL> for each file (with 123456.123 being the last modification time of the files).

We're sorting that numerically (so the newest file comes first) and then using awk to find the ones that are more than 10 days older than the newest file (found in the first record in that sorted list).

0

I feel below command would help if you are working on Linux based Operating system.

find /path/to/directory/ -mindepth 1 -mtime +7 -delete

+7 = variable which means files older than 7 days will be deleted

Be careful with spaces, quotes to rm.

  • But that doesn’t answer the question, which is about deleting the latest modified file and files older than 10 days. – Stephen Kitt Jul 24 '18 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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