How to remove only files created before a specific date and time

12,394

Linux doesn't keep record of creation time, there are only 3 time records for files: last access, last modification of contents and last modification of the inode. So you are left with 3 options:

To delete all files modified before 04/29/2018 at 4:00 pm:

find . -type f ! -newermt '04/29/2018 16:00:00' -exec rm -f {} \;

To delete all files accessed before 04/29/2018 at 4:00 pm:

find . -type f ! -newerat '04/29/2018 16:00:00' -exec rm -f {} \;

To delete all files which had their permission changed before 04/29/2018 at 4:00 pm:

find . -type f ! -newerct '04/29/2018 16:00:00' -exec rm -f {} \;

You probably wouldn't want to run the above commands as root, and remember to backup any important files.

Important note!

You should treat date values with caution. Even though I did a complete format to my hard drive last month, I have some files in my home directory dating back to 2014!

Sources: [1][2][3]

Share:
12,394

Related videos on Youtube

vincet
Author by

vincet

Updated on September 18, 2022

Comments

  • vincet
    vincet over 1 year

    l would like to remove from my directory files which have been created before 04/29/2018 at 4:00 pm.

    Thank you

  • dessert
    dessert about 6 years
    find also has the -delete option which you can use instead of -exec rm -f {} \;, this saves you the call of rm for every single match. Both are to handle with great care: 1) Always have a backup at hand. 2) First print the matches, i.e. execute find without any -delete or -exec options. 3) Check very carefully! 4) Run find with -delete.
  • dessert
    dessert about 6 years
    A safer alternative for -exec in this context is -ok, which asks for every match – or one can make rm ask with -exec rm -i {} \;. Unless you have a lot of files/directories to delete, -exec … {} + will work as well and be faster.
  • mook765
    mook765 almost 5 years
    Linux doesn't keep record of creation time. That's not true, see unix.stackexchange.com/questions/91197/…