Finding Files by Date

Problem

Suppose someone sent you a JPEG image file that you saved on your filesystem a few months ago. Now you don’t remember where you put it. How can you find it?

Solution

Use a find command with the -mtime predicate, which checks the date of last modification. For example:

find . -name '*.jpg' -mtime +90 -print

Discussion

The -mtime predicate takes an argument to specify the timeframe for the search. The 90 stands for 90 days. By using a plus sign on the number (+90) we indicate that we’re looking for a file modified more than 90 days ago. Write -90 (using a minus sign) for less than 90 days. Use neither a plus nor minus to mean exactly 90 days.

There are several predicates for searching based on file modification times and each take a quantity argument. Using a plus, minus, or no sign indicates greater than, less than, or equals, respectively, for all of those predicates.

The find utility also has logical AND, OR, and NOT constructs so if you know that the file was at least one week old (7 days) but not more than 14 days old, you can combine the predicates like this:

$ find . -mtime +7 -a -mtime -14 -print

You can get even more complicated using OR as well as AND and even NOT to combine conditions, as in:

$ find . -mtime +14 -name '*.text' -o \( -mtime -14 -name '*.txt' \) -print

This will print out the names of files ending in .text that are older than 14 days, as well as those that are newer than 14 days but have .txt as their last 4 characters.

You will likely need ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.