The Linux Page

Sorting files by last modification date when found with "find"

Sorted desktop items in various jars made of glass.

We often want to sort filenames by date. It's easy enough with the ls command we use the -t command line option.

ls -t

Then we can use the -r to reverse the list which means we see the last modified file at the end of the list.

ls -tr

Futher I tend to use the -l to see more details when listing and verify that my command does what I expect it to do.

Now there are situations where a more complex search than a simple shell glob is necessary. For example, looking for a file that includes the name '*linux*' in a whole tree of files would go like this:

find path-to-search -name linux

Only that command does not return the files in a controlled order. Instead it will return them in the order they were found on the disk (so not some random order, but one which usually does not make sense—this order may represents the order in which order the files were created).We can use the find function to find the files. To allow for the sort by date, we use the -printf command line option and include  the date first in seconds ("%A@"). This value can be sorted with the simple sort command.

Here is an example of such a command line:

find . -type f -printf "%A@ %p\n" | sort | less

This find pints out the name of all the flles in the tree starting at ".". The -printf allows us to get exactly the fields we're interested in. Here I get the time in seconds and then the filename. Therefore the sort will sort by last modification time. We could further use cut to remove the date from the final output.

Bug: Note that the above has a bug because the -printf will not include leading zeroes and the sort will fail when the number of digits in the timestamp changes (i.e. 4 is after 30, however 04 is before 30).