How can I make `find` find files in reverse chronological order?

17

3

I want to find files in subdirectories sorted by timestamp (of creation), with most recent first.

I have looked at the man page but it seems to only seems to let you filter by timestamp rather than sort by timestamp.

What options can I pass to find to accomplish this? Alternately, how can I combine it with another tool, like sort to sort by timestamp?

merlin2011

Posted 2013-06-17T22:23:02.557

Reputation: 1 409

@merlin2011, please review your selection of answers here -- the presently-selected answer is buggy (will generate outputs which are not actually correctly sorted) when there are more files found by find than can be passed to a single instance of ls. – Charles Duffy – 2018-02-28T02:45:42.520

@CharlesDuffy, Thanks for the note! I've updated the accepted answers. – merlin2011 – 2018-02-28T03:30:01.977

1You can't make find do anything in a particular sorted order, beyond choosing between a depth-first search and a breadth-first search. – Jonathan Leffler – 2013-06-18T02:34:45.333

Answers

32

While Paul's solution is generally OK, it involves more I/O than simply:

find bin/ -type f -printf '%Ts\t%p\n' | sort -nr | cut -f2

user7385

Posted 2013-06-17T22:23:02.557

Reputation:

What if find returns millions of files? Isn't sort going to sort all of them as one very long list? Is it still going to be efficient? (Instead of sorting each directory independently.) – Peter Mortensen – 2017-06-13T22:29:38.963

1Doesn't work with funny characters in file names, like newlines – Boris Brodski – 2017-11-23T09:29:42.530

2This deserves only a comment on user7385's answer, but I don't have the reputation to do that. find bin/ -type f -printf '%Ts\t%p\0' | sort -nrz | cut -f2 -z | xargs -0 ls New versions of cut have the -z option, so filenames with newlines would work. – MattBlissett – 2018-01-16T13:24:32.707

The amount of I/O isn't even the primary reason to prefer this answer -- correctness is a much more critical distinction. The xargs -0 ls -t approach won't work correctly when there are so many files that xargs needs to start ls more than once, but this approach will continue to function. – Charles Duffy – 2018-02-28T02:44:40.240

@PeterMortensen, "sorting them all as one very long list" is the only way to sort them that actually returns a correct result. Moreover, the other/accepted answer doesn't "sort each directory independently" either (if one wanted to sort only a single directory without recursing, one might use -maxdepth 1 on the find). – Charles Duffy – 2018-02-28T02:48:17.393