72

I used the below command to delete files older than a year.

  find /path/* -mtime +365 -exec rm -rf {} \;

But now I want to delete all files whose modified time is older than 01 Jan 2014. How do I do this in Linux?

4 Answers 4

72

This works for me:

find /path ! -newermt "YYYY-MM-DD HH:MM:SS" | xargs rm -rf
4
  • 3
    this is very nice, I don't pollute filesystem with temp timestamp file!
    – andrej
    Apr 25, 2018 at 9:13
  • 12
    For just files find /path ! -type f -newermt "YYYY-MM-DD HH:MM:SS" -delete. It saves you from having to pipe everything through xargs, and having to handle filesnames with spaces or other disruptive characters.
    – jbo5112
    Sep 20, 2019 at 20:33
  • For what it's worth, -newermt is a non-standard extension, though on Linux systems you will typically have GNU find. This is not portable to other platforms.
    – tripleee
    Mar 24, 2021 at 7:49
  • Adding -delete argument to the find command also works. Oct 29, 2021 at 8:53
37

You can touch your timestamp as a file and use that as a reference point:

e.g. for 01-Jan-2014:

touch -t 201401010000 /tmp/2014-Jan-01-0000

find /path -type f ! -newer /tmp/2014-Jan-01-0000 | xargs rm -rf 

this works because find has a -newer switch that we're using.

From man find:

-newer file
       File  was  modified  more  recently than file.  If file is a symbolic
       link and the -H option or the -L option is in effect, the modification time of the 
       file it points to is always used.
3
  • 3
    Thank you. ! is as good as -not "find . -not -newer /tmp/2014-Jan-01-0000 "
    – VRK
    Oct 13, 2015 at 16:22
  • 3
    this is polluting the file system. -newer(a/b/c/m/t) timestamp can do it efficiently. please update your answer
    – yoga
    Jul 2, 2019 at 20:00
  • @yoga Or just delete the file when you're done. It's literally in the "temporary files" directory May 2, 2021 at 3:23
26

This other answer pollutes the file system and find itself offers a "delete" option. So, we don't have to pipe the results to xargs and then issue an rm.

This answer is more efficient:

find /path -type f -not -newermt "YYYY-MM-DD HH:MI:SS" -delete
2
  • 1
    The data fmt is wrong: use find /path -type f -not -newermt "YYYY-MM-DD HH:MI:SS" -delete
    – josef
    Oct 14, 2019 at 5:30
  • This seems to repeat an older answer from 2017, though the -delete option is an improvement.
    – tripleee
    Mar 24, 2021 at 7:50
4
find ~ -type f ! -atime 4|xargs ls -lrt

This will list files accessed older than 4 days, searching from home directory.

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.