Situation: We need to delete the files older than 30 days
To delete the files in directory older than certain number of days (30 in this case) we can use find command in combination with rm.
Command: find /path/to/files -type f -mtime +30 -exec rm {} \;
example: find /u01/app/audit -type f -mtime +30 -exec rm {} \;
To delete files having certain pattern (*txt in this case) in the name we can use below:
Command: find /path/to/files -type f -name "*.txt" -exec rm {} \;
example: find /u01/app/audit -type f -name "*.txt" -mtime +30 -exec rm {} \;
As precautionary step, you can also list files before deletion:
Command: find /path/to/files -type f -name "*.txt" -mtime +30 -exec ls {} \;
example: find /u01/app/audit -type f -name "*.txt" -mtime +30 -exec ls {} \;
How does the ‘find’ command work
When fired, find will look into provided path. Expression is the criteria for selecting the files.
We use below optional parameters
-type f : Command should consider only regular files
-name “*txt” : Files with expression “txt” should be considered
-exec ls {} \; : The files which are found execute ‘ls’ on them
Search Process for command find /u01/app/audit -type f -name “*.txt” -mtime +30 -exec ls {} \;
find looks into specified path (/u01/app/audit) and recursively will explore sub-directories as well. The files which are found with pattern ‘*txt’ will have execution of ls command on them.