When I use the locate command, I often wish that the output was sorted in reverse chronological order, just like with ls -rtc. What is the easiest way to achieve this?

  • 1
    I realized that this answer is relevant: superuser.com/a/251432/576570 However, it seems one should pass --full-time to ls in order to get a field which is sortable (as well as -d so you don't list directories). Mar 29, 2016 at 19:50

1 Answer 1


The easiest way to achieve this is to pipe your list of files through a sequence of commands:

locate your-search-term |
  xargs stat --printf '%.Y\t%n\n' |
  sort -n -r |
  cut -f 2-

The first line locates your files — you know this already. The second line stat-s a file and prints the last modification time (epoch seconds) and the file path, for each located filename. The third line sorts the lines numerically descending. The last line cuts the modification time and the separator from each line, leaving the original path.

  • 1
    Thank you, I'll put this in a little script in my home directory. I didn't know about stat before. By the way, I use locate -0 and xargs -0 so that filenames with spaces come out OK. Mar 30, 2016 at 22:36
  • That's a good practice (i.e. NIL-separated paths) when you expect whitespace in the paths. Esp. newlines can be troublesome here, they will destroy sort (which can be overcome by adding -z switch) and cut (which may be overcome by replacing cut with perl -p0e 's/^\S*\s+//')
    – pwes
    Mar 31, 2016 at 7:22
  • 1
    I created a script called time-sort-files with contents: tr '\n' '\0' | xargs -0 stat --printf '%.Z\t%z\t%n\0' | sort -zn | cut -z -f 2- | tr '\0' '\n' | sed 's/:..\..*\t/\t/' It also prints dates next to each file. The initial tr makes it so I can pipe an ordinary newline-separated file list into time-sort-files. The sort lacks -r because I actually wanted chronological order (I said "reverse" by mistake!), like ls -rt. Thanks again! Apr 8, 2016 at 2:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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