Wednesday, 18 April 2012

Using unix find Command to delete files older than a year

One of the boring task is to clean up data when ever disk usage exceeds the threshold limit. Among the many ways do it, here is the simple usage of Unix find command to delete files older than a year.

   find . -type f -mtime +365 -delete

Where -mtime +365 suggests to list files older than 365 days.
or
  find . -type f -atime +365 -delete

Where -atime stands for access time which is when the file was last read.


Some more examples

find . -mtime 0 # find files modified between now and 1 day ago 
# (i.e., within the past 24 hours)


find . -mtime -1 # find files modified less than 1 day ago 
# (i.e., within the past 24 hours, as before)

find . -mtime 1 # find files modified between 24 and 48 hours ago 

find . -mtime +1 # find files modified more than 48 hours ago

find . -mmin +5 -mmin -10 # find files modified between 
# 6 and 9 minutes ago


Usage of -exec option 
Here is the simple use case.
I want to find all the files with the name 'latest' in a directory and I want to run 'ls -l' command on the result, since I want to know whether 'latest' is a directory or soft link.
find . -maxdepth 2 -name latest -exec ls -l '{}' \;
Here the 
  -maxdepth option restrict the search to be conducted 2 levels of directory hierarchy.
The syntax '{}' \; is mandatory, which is tedious.

No comments:

Post a Comment