Better Living Through Thinking

Find files older than a given time

Tue, 05 Dec 2006

We want to find files that are older than a specified time. We use the '-newer' option to 'find' and invert it. The BSD 'find(1)' manpage states:

-newerXY file
  True if the current file has a more recent last access time (X=a),
  change time (X=c), or modification time (X=m) than the last access
  time (Y=a), change time (Y=c), or modification time (Y=m) of file.
  In addition, if Y=t, then file is instead interpreted as a direct
  date specification of the form understood by cvs(1).

This means that if we substitute 'X' with 'm' and 'Y' with 't', we can specify a cvs time specification to compare against:

find . -type f -newermt "52 seconds ago" -print

This will find files newer than 52 seconds old. To get older files, we just invert the '-newermt' specification:

find . -type f ! -newermt "52 seconds ago" -print

Now we find files *older* than 52 seconds. If we want to do anything with the files, we'll need to not forget to null-terminate the output file names in case we have files with space characters in it (which 'xargs' would normally use to split on):

find . -type f ! -newermt "52 seconds ago" -print0 | xargs -0 rm -f

This deletes all files older than 52 seconds found in the current directory ('.').

Other valid time specifications (per the cvs(1) manpage):

1 month ago
2 hours ago
400000 seconds ago
last year
last Monday
yesterday
a fortnight ago
3/31/92 10:00:07 PST
January 23, 1987 10:05pm
22:00 GMT

Some systems allow the '-mmin' option:

find . -type f -mmin +60 -print

which accomplishes the same thing (finds files modified older than 1 hour ago) but more concisely (albeit with less flexibility and granularity).

Why 'xargs' instead of find's '-exec' option? In general, when operating on many files, 'xargs' will batch files where '-exec' will fork once for *each file*.

<dmiessler.com/archives/986>

[ category: /sysadmin | link: find_older ]

Audio Broadcast

(standby)

Moon Status

Phase: 64.15%
Illuminated: 81.51%
Age (days): 18.94
moon phase 0.641494420588321 Fri Jul 30 11:07:09 MDT 2010