Home / Find and delete older files

Find and delete older files

In a Linux server, finding and deleting files older than 7 days can be done as follows.

  • You should use the find command to get a list of files older than 7 days with the following command.

# find /directory-path -mtime +7 -type f -exec ls {} ;

  • In case, files you are looking for start with a particular pattern, filter that as follows.

find /directory-path -name 'filename*' -mtime +7 -type f -exec ls {} ;

  • Check the output of the above command, append the removal options in the command, else there is risk of data loss.

find /directory-path -name 'filename*' -mtime +7 -type f -exec rm -fv {} ;

  • If you want to find and delete files on a remote server by connecting through ssh, running a corn job, and log the names of deleted files, do as follows.

# ssh user@ip-remote-server "find /directory-path -name 'filename*' -mtime +7 -type f -exec rm -fv {} ; >> /tmp/backup_deletion`date +%Y%m%d`.log 2>&1"

 

 

 

Leave a Reply