List most recently modified files in a `ls`-style output without running `ls` on the entire directory

datefilesls

I have a directory with tens of thousands of files. I want to list the most recently modified files (for example files modified within the last day or whatever).

The following command works but is slow because it has to ls every file in the folder:

ls -rt | tail -n 10

The following command is faster but the output is not as detailed as ls:

find -mtime -1

Is there a way I can list the most recently modified files (either a set number or by date) with ls-like output but faster?

Best Answer

At least the GNU and FreeBSD finds have the -ls action, which produces output similar to ls:

$ find . -ls
   392815      4 drwxr-xr-x   2 user  group      4096 Jul 22 18:39 .
   392816      0 -rw-r--r--   1 user  group         0 Jul 22 18:39 ./foo.txt
   392818      0 -rw-r--r--   1 user  group         0 Jul 22 18:39 ./bar.txt

GNU find also has very configurable output in the form of the -printf action.

That said, I do wonder what makes your ls so slow. Both find and ls need to read the whole directory and call lstat() on all the files to find the dates, so there shouldn't be much of a difference. ls does need to sort the whole list of files, so that could make a difference if there is a really large number of files. In that case, you might want to consider spreading the files out to different directories, possibly based on their date. Dropping the -r and use head instead of tail might help.

Related Question