PureDevOps Community

Remove Files Older Than 7 days or any days in linux

The command to remove older than 7 days and it can be customised upto one’s convenience

This will remove all files under the path

find /path/to-directory/ -type f -mtime +7 -name '*' -execdir rm -- '{}' \;

for a specific type of files

find /path/to/ -type f -mtime +7 -name '*.gz' -execdir rm -- '{}' +

Explanation:

  • find: the unix command for finding files/directories/links and etc.
  • /path/to/: the directory to start your search in.
  • -type f: only find files.
  • -name '*.gz': list files that ends with .gz.
  • -mtime +7: only consider the ones with modification time older than 7 days.
  • -execdir ... \;: for each such result found, do the following command in ....
  • rm -- '{}': remove the file; the {} part is where the find result gets substituted into from the previous part. -- means end of command parameters avoid prompting error for those files starting with hyphen.

others :

find /path/to/ -type f -mtime +7 -name '*.gz' -delete
find /path/to/ -type f -mtime +7 -name '*.gz' -execdir rm -- '{}' +