Tuesday, June 14, 2011

Unix: Finding files or directories based on their timestamp or age using a resolution finer than of days

When you use the –mtime option, the typical find command’s granularity is in terms of days i.e. how many days old. To effectively get finer granularity with the find command  i.e. to be able to specify hours, minutes or even seconds, warrants an indirect approach.

Suppose I have a directory within which I would like to search for files/directories that are older or newer than 2 hours from current time:



$ ls -ltr
total 0
-rw-r--r-- 1 ramesh users 0 2010-05-15 18:34 file_1
-rw-r--r-- 1 ramesh users 0 2011-06-15 03:00 file_2
-rw-r--r-- 1 ramesh users 0 2011-06-15 09:16 file_5
-rw-r--r-- 1 ramesh users 0 2011-06-15 09:16 file_4
-rw-r--r-- 1 ramesh users 0 2011-06-15 09:16 file_3

**  The command ls -ltr  lists our directory entries with the later ones at the bottom.


Current time is:

$ date
Wed Jun 15 09:19:23 MYT 2011


I create a (dummy) reference file with a time stamp of 2 hours earlier which is 15-June-2011  07:19:23:

$ touch -t 201106150719.23 ref_timestamp_file
$ ls -ltr
total 0
-rw-r--r-- 1 ramesh users 0 2010-05-15 18:34 file_1
-rw-r--r-- 1 ramesh users 0 2011-06-15 03:00 file_2
-rw-r--r-- 1 ramesh users 0 2011-06-15 07:19 ref_timestamp_file
-rw-r--r-- 1 ramesh users 0 2011-06-15 09:16 file_5
-rw-r--r-- 1 ramesh users 0 2011-06-15 09:16 file_4
-rw-r--r-- 1 ramesh users 0 2011-06-15 09:16 file_3


To find files and directories created after the reference time-stamp file i.e. created after 7:16 A.M. on 15-June-2011, use the newer option of find command:

$ find . -newer ref_timestamp_file
.
./file_5
./file_4
./file_3


And to get files which are older than the reference time-stamp file i.e. created before 7:16 A.M. on 15-June-2011, just negate the result of the find command:

$ find . ! -newer ref_timestamp_file
./file_2
./file_1
./ref_timestamp_file