Use find, wc, and sed to count lines


Question

I was trying to use sed to count all the lines based on a particular extension.

find -name '*.m' -exec wc -l {} \; | sed ...

I was trying to do the following, how would I include sed in this particular line to get the totals.

1
24
9/11/2009 5:24:25 PM

Accepted Answer

You may also get the nice formatting from wc with :

wc `find -name '*.m'`
46
9/11/2009 5:37:47 PM

Most of the answers here won't work well for a large number of files. Some will break if the list of file names is too long for a single command line call, others are inefficient because -exec starts a new process for every file. I believe a robust and efficient solution would be:

find . -type f -name "*.m" -print0 | xargs -0 cat | wc -l

Using cat in this way is fine, as its output is piped straight into wc so only a small amount of the files' content is kept in memory at once. If there are too many files for a single invocation of cat, cat will be called multiple times, but all the output will still be piped into a single wc process.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon