What is the best way to count "find" results?

MechMK1 picture MechMK1 · Mar 27, 2013 · Viewed 85.3k times · Source

My current solution would be find <expr> -exec printf '.' \; | wc -c, but this takes far too long when there are more than 10000 results. Is there no faster/better way to do this?

Answer

Brian Agnew picture Brian Agnew · Mar 27, 2013

Why not

find <expr> | wc -l

as a simple portable solution? Your original solution is spawning a new process printf for every individual file found, and that's very expensive (as you've just found).

Note that this will overcount if you have filenames with newlines embedded, but if you have that then I suspect your problems run a little deeper.