Search code examples
linuxfindls

Find and sort files by date modified


I know that there are many answers to this question online. However, I would like to know if this alternate solution would work:

ls -lt `find . -name "*.jpg" -print | head -10`

I'm aware of course that this will only give me the first 10 results. The reason I'm asking is because I'm not sure whether the ls is executing separately for each result of find or not. Thanks


Solution

  • In your solution:

    • the ls will be executed after the find is evaluated
    • it is likely that find will yield too many results for ls to process, in which case you might want to look at the xargs command

    This should work better: (format is for MacOS)

      find . -type f -print0 | xargs -0 stat -f"%m %Sm %N" | sort -rn 
    

    The three parts of the command to this:

    • find all files and print their path
    • use xargs to process the (long) list of files and print out the modification unixtime, human readable time, and filename for each file
    • sort the resulting list in reverse numerical order

    The main trick is to add the numerical unixtime when the files were last modified to the beginning of the lines, and then sort them.