Find and Remove Files Modified / accessed N days ago - Unix / Linux

Q) How to find the files which were modified or accessed N or more days ago and then delete those files using the unix or linux command?

Searching for the files which were modified (or accessed) 10 or more days ago is common operation especially when you want to archive or remove older log files. Let see this with the help of an example.

Let see the todays date in my unix Operating system by issuing the date command. Here i am providing this date just for reference to N days.

date
Mon Jul 2 03:17:59 PDT 2012

We can use the find command for searching the files modified N or more days ago. The find command for this is:

find . -mtime +N

As an example, lets list out the files modified 5 days ago. The unix command for this is:

find . -mtime +5
./fedora.dat
./bsd.txt

We got the list of files. Next we have to delete these files. We have to use the rm command in unix for removing the files. One way of removing the files is piping the output of find command to xargs. This is shown below:

find . -mtime +5 | xargs rm

The find command itself has the capability of executing the commands on the files it listed. We have to use the exec option in the find command. The complete find command for deleting the files modified N days ago is

find . -mtime +5 -exec rm {} \;

Note: To remove the files based on access time use the -atime in the find command.