Crash Override Crash Override - 1 month ago 10
Linux Question

Linux Shell Command: Find. How to Sort and Exec without using Pipes?

Linux command

find
with argument
exec
does a GREAT job executing commands on files/folders regardless whether they contain spaces and special characters. For example:

find . -type f -exec md5sum {} \;


Works great to run
md5sum
on each file in a directory tree, but executes in a random order. Find does not sort the results, and requires piping to
sort
to get results in a more human-readable ordering. However, piping to
sort
eliminates the benefits of
exec
.

This does not work:

find . -type f | sort | md5sum


Because some filenames contain spaces and special characters.

Also does not work:

find . -type f | sort | sed 's/ /\\ /g' | md5sum


Still does not recognize spaces are part of the filename.

I suppose I can always sort the final result later, but wonder if someone knows an easy way to avoid that extra step by sorting within
find
?

Answer

With BSD find

A -s argument is available to request lexographic sort order.

find . -s -type f -exec md5sum -- '{}' +

With GNU find

Use NUL delimiters to allow filenames to be processed unambiguously. Assuming you have GNU tools:

find . -type f -print0 | sort -z | xargs -0 md5sum
Comments