Tuesday, November 2, 2021

[SOLVED] What is the best way to count "find" results?

Issue

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?


Solution

Try this instead (require find's -printf support):

find <expr> -type f -printf '.' | wc -c

It will be more reliable and faster than counting the lines.

Note that I use the find's printf, not an external command.


Let's bench a bit :

$ ls -1
a
e
l
ll.sh
r
t
y
z

My snippet benchmark :

$ time find -type f -printf '.' | wc -c
8

real    0m0.004s
user    0m0.000s
sys     0m0.007s

With full lines :

$ time find -type f | wc -l
8

real    0m0.006s
user    0m0.003s
sys     0m0.000s

So my solution is faster =) (the important part is the real line)



Answered By - Gilles Quenot