Find – How to Sort Output of find -exec ls

findlssort

Is it possible to the output of find … -exec ls -ls ; sorted alpabetically, by filename?

This is my cron command:

find /home/setefgge/public_html -type f -ctime -1 -exec ls -ls {} \;

This command works okay, for the most part. But the results are not sorted in any meaningful sequence. It would be very helpful if they would be sorted by the file name field.

Best Answer

I assume that your file names don't contain newlines.

find /home/setefgge/public_html -type f -ctime -1 -exec ls -nls {} + | sort -k 10

Using + instead of ; to terminate the -exec action makes it faster by batching the invocations of ls. You can sort by piping through the sort command; tell it to start sorting at the 10th field (the first 9 are the metadata: blocks, permissions, link count, user, group, size, and 3 date/time fields). The option -n tells ls to use numeric values for the user and group, which avoids the risk of user or group names containing whitespace.

Alternatively, with zsh, you can get away with no assumption on any name by using glob qualifiers to collect and sort the files and zargs to run ls multiple times if the command line would be too long. You do need GNU ls (specifically its -f option) to avoid re-sorting by ls (another approach would be to emulate ls with zsh's zstat).

autoload -U zargs
zargs -- /home/setefgge/public_html/**/*(.c-2) -- ls -lnsf
Related Question