how do I sort the output of 'locate' by file modification time

0

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?

Metamorphic

Posted 2016-03-29T19:41:50.890

Reputation: 325

1

I realized that this answer is relevant: http://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).

– Metamorphic – 2016-03-29T19:50:54.953

Answers

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.

pwes

Posted 2016-03-29T19:41:50.890

Reputation: 126

1Thank 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. – Metamorphic – 2016-03-30T22:36:16.470

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 – 2016-03-31T07:22:12.547

1I 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! – Metamorphic – 2016-04-08T02:20:05.270