Wednesday, April 18, 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.

Unix find command to list files greater than 10MB
find . -size +10M -exec ls -lh '{}' \;

Unix find files older than 50 days and move them to another folder
find . -type f -mtime +50 -print| xargs -I {} mv {} /homes/siddesh/psbuild-portal-CGITemp-files

2 comments:

Browngdvo said...

But on the other hand, neither would we have most of humanity's chronic ills including whole-scale warfare, starvation, tyranny, infectious epidemics and chronic diseases.[2]. Please remember this when using this information to make healthy food choices for your diet. Learn about the number of calories and nutritional and diet information for Barbara's Bakery Weetabix/alpen Cereal, Original. The Hollywood Canteen was a nightclub where soldiers passing through Los Angeles during World War II got to see Hollywood stars perform live on stage.

vijay @ unix commands said...

Nice post:
find command.
Thanks for sharing.