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 parentheses to get the precedence right. Two predicates in sequence are like a logical AND, which binds tighter than an OR (in find as in most languages). Use parentheses as much as you need to make it unambiguous.

Parentheses have a special meaning to bash, so we need to escape that meaning, and write them as ( and ) or inside of single quotes as '(' and ')'. You cannot use single quotes around the entire expression though, as that will confuse the find command. It wants each predicate as its own word.

See Also

  • man find

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.15.100