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 Answer
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.
-
2Thank you, I'll put this in a little script in my home directory. I didn't know about
stat
before. By the way, I uselocate -0
andxargs -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) andcut
(which may be overcome by replacingcut
withperl -p0e 's/^\S*\s+//'
)– pwesMar 31, 2016 at 7:22 -
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 initialtr
makes it so I can pipe an ordinary newline-separated file list intotime-sort-files
. Thesort
lacks-r
because I actually wanted chronological order (I said "reverse" by mistake!), likels -rt
. Thanks again! Apr 8, 2016 at 2:20
--full-time
tols
in order to get a field which is sortable (as well as-d
so you don't list directories).