Recursively find all files newer than a given time

Viewed 172495

Given a time_t:

⚡ date -ur 1312603983
Sat  6 Aug 2011 04:13:03 UTC

I'm looking for a bash one-liner that lists all files newer. The comparison should take the timezone into account.

Something like

find . --newer 1312603983

But with a time_t instead of a file.

9 Answers

Assuming a modern release, find -newermt is powerful:

find -newermt '10 minutes ago' ## other units work too, see `Date input formats`

or, if you want to specify a time_t (seconds since epoch):

find -newermt @1568670245

For reference, -newermt is not directly listed in the man page for find. Instead, it is shown as -newerXY, where XY are placeholders for mt. Other replacements are legal, but not applicable for this solution.

From man find -newerXY:

Time specifications are interpreted as for the argument to the -d option of GNU date.

So the following are equivalent to the initial example:

find -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d '10 minutes ago')" ## long form using 'date'
find -newermt "@$(date +%s -d '10 minutes ago')" ## short form using 'date' -- notice '@'

The date -d (and find -newermt) arguments are quite flexible, but the documentation is obscure. Here's one source that seems to be on point: Date input formats

There is PowerShell available on Linux for some time so I recommend to use that since it does not deal just with pure text but handles real objects and so avoids formatting and make the task much easier

ls -recurse | where lastwritetime -gt ((get-date).AddDays(-1))

It's another way. You can recursively find files newer than a given timestamp using touch -d and find /dir -newer commands.

For example, if you need find files newer than '1 June 2018 11:02', you can create a file with this creation date.

touch -d '1 June 2018 11:02' ref_timestamp

Then, you can use the file timestamp as reference in find command.

find /dir -newer ref_timestamp

So there's another way (and it is portable to some extent_

(python <<EOF
import fnmatch
import os
import os.path as path
import time

matches = []
def find(dirname=None, newerThan=3*24*3600, olderThan=None):
    for root, dirnames, filenames in os.walk(dirname or '.'):
        for filename in fnmatch.filter(filenames, '*'):
            filepath = os.path.join(root, filename)
            matches.append(path)
            ts_now = time.time()
            newer = ts_now - path.getmtime(filepath) < newerThan
            older = ts_now - path.getmtime(filepath) > newerThan
            if newerThan and newer or olderThan and older: print filepath
    for dirname in dirnames:
        if dirname not in ['.', '..']:
            print 'dir:', dirname
            find(dirname)
find('.')
EOF
) | xargs -I '{}' echo found file modified within 3 days '{}'
Related