The find command in Linux has many options and arguments that can be used, including the ability to run another command for each file. On this basis, it is possible to find which files are older than a certain number of days and, for example, use the rm command to delete them.
The syntax for finding and deleting, for example, files older than 5 days:
# find /ruta/de/los/archivos* -mtime +5 -type f -exec rm {} \;
Code explanation:
- The first argument “/ruta/de/los/archivos*” is the path to the files. We recommend using the absolute path and, before using the command, testing it without the rm command to make sure you are getting the desired results.
- The second argument “-mtime“, is used to specify how many days old the file must be for the second part to run. In this case, “+5” indicates that you want to find files older than 5 days.
- The third argument “-type“, is used to specify what we are looking for; in this case, “f” indicates that we are looking only for files (Files in English).
- The fourth argument “-exec“, lets you run a command on the results, such as “rm“.
- Finally, to close the command, specify “{} \;“.