Linux: Delete Files Older Than X Days

Published on November 20, 2019 10:49:24PM by Administrator

This is a simple tutorial on how to find and delete files older than "X" days. With this you will be able with the Linux find command to find your CSV files older then 30 days and then execute rm command on them.


Linux: Delete Files Older Than X Days

Delete command

find /path/to/files/ -type f -name '*.csv' -mtime +30 -exec rm {} \;

Explanation

  1. First part is the path where your files are located. Don’t use wildcard * if you have a lot of files because you will get Argument list too long error.
  2. Second part -type is the file type f stands for files
  3. Third part -name is limiting *,csv files
  4. Fourth part -mtime gets how many days the files older then will be listed. +30 is for files older then 30 days.
  5. Fifth part -exec executes a command. In this case rm is the command, {} gets the filelist and \; closes the command


Move command

find /path/to/files/ -type f -name '*.csv' -mtime +30 -exec mv {} /path/to/archive/ \;

Explanation

  1. First part is the path where your files are located. Don’t use wildcard * if you have a lot of files because you will get Argument list too long error.
  2. Second part -type is the file type f stands for files
  3. Third part -name is limiting *,csv files
  4. Fourth part -mtime gets how many days the files older then will be listed. +30 is for files older then 30 days.
  5. Fifth part -exec executes a command. In this case mv is the command, {} gets the filelist, path where to move the files and \; closes the command