94

I want to use find but sort the results reverse chronologically as with ls -ltr. Is this possible through any combo of flags or pipelines?

4
139

Use find's -printf command to output both the time (in a sortable way) and the file, then sort. If you use GNU find,

find . your-options -printf "%T+ %p\n" | sort

For convenience here is an explanation of the -printf "%T+ %p\n" from man find:

  • %Tk File's last modification time in the format specified by k, which is the same as for %A.
    • where k in this case is set to +
    • + Date and time, separated by +, for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part.
  • %p File's name.
12
  • 7
    sort -r for reverse order. – stnly Jan 24 '12 at 15:12
  • 8
    ls -t sorts newer to older, sort sorts older to newer. So ls -t's reverse order is sort's normal order. – angus Jan 24 '12 at 15:19
  • 1
    Do you have a version for OS X (non-gnu)? – Ortomala Lokni Aug 25 '16 at 15:48
  • 6
    For OS X and non-GNU, use this answer. – Tom Hale Jan 11 '17 at 4:46
  • 6
    To get this to work with OSX, install findutils from homebrew, then use gfind not find. stackoverflow.com/questions/752818/… – Chris Mar 5 '18 at 0:44
4

If that is just a depth-n (assume depth-2) folder hierarchy, I find this one useful:

ls -laht --full-time */*
4
  • This seems to produce a list of files that are exactly two folders deep (no more, no less), along with separate listings of each of the folders that are exactly two folders deep. – mwfearnley Feb 12 '17 at 13:42
  • 2
    @mwfearnley that is exactly what I meant by "that is just a depth-n" above :) you can do */*/* if you want depth 3 – Ben Usman Feb 13 '17 at 17:25
  • 2
    So basically, your suggestion only works as intended when all the files are exactly n levels deep, and there are no subfolders at that level. You should explain that. The latter might be surmountable by another flag for ls, and you can perhaps cover all levels up to n with ls ... * */* */*/* ... – mwfearnley Feb 14 '17 at 9:26
  • May not work: bash: /bin/ls: Argument list too long – Luc Jan 13 '20 at 10:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.