Ubuntu – Find the latest file by modified date

command linefind

If I want to find the latest file (mtime) in a (big) directory containing subdirectories, how would I do it?

Lots of posts I've found suggest some variation of ls -lt | head (amusingly, many suggest ls -ltr | tail which is the same but less efficient) which is fine unless you have subdirectories (I do).

Then again, you could

find . -type f -exec ls -lt \{\} \+ | head

which will definitely do the trick for as many files as can be specified by one command, i.e. if you have a big directory, -exec...\+ will issue separate commands; therefore each group will be sorted by ls within itself but not over the total set; the head will therefore pick up the lastest entry of the first batch.

Any answers?

Best Answer

You do not need to recur to external commands (as ls) because find can do all you need through the -printf action:

find /path -printf '%T+ %p\n' | sort -r | head