How to use GNU find command to find files by pattern and list files in order of most recent modification to least?

535 views Asked by At

I want to use the GNU find command to find files based on a pattern, and then have them displayed in order of the most recently modified file to the least recently modified.

I understand this:

find / -type f -name '*.md'

but then what would be added to sort the files from the most recently modified to the least?


3

There are 3 answers

0
Raman Sailopal On
find <dir> -name "*.mz" -printf "%Ts - %h/%f\n" | sort -rn

Print the modified time in epoch format (%Ts) as well as the directories (%h) and file name (%f). Pipe this through to sort -rn to sort in reversed number order.

1
Timur Shtatland On

Pipe the output of find to xargs and ls:

find / -type f -name '*.md' | xargs ls -1t
0
that other guy On

find can't sort files, so you can instead output the modification time plus filename, sort on modification time, then remove the modification time again:

find . -type f -name '*.md' -printf '%T@ %p\0' |   # Print time+name
  sort -rnz |                                      # Sort numerically, descending
  cut -z -d ' ' -f 2- |                            # Remove time
  tr '\0' '\n'                                     # Optional: make human readable

This uses \0-separated entries to avoid problems with any kind of filenames. You can pass this directly and safely to a number of tools, but here it instead pipes to tr to show the file list as individual lines.