Linux – How to find the total number of lines in a set of found files (using Linux command-line tools)

command-line-interfacefindlinux

I can find the number of lines of each file matching a particular pattern using (for example):

$ find . -name "test.save*" -exec wc -l {} \;
673000 ./test.save8.txt
24000 ./from/test1/test.save3.txt
100 ./from/test1/test.save1.txt
513000 ./from/test1/test.save2.txt
2253000 ./from/test1/test.save4.txt
2252000 ./from/test2/test.save3.txt
100 ./from/test2/test.save1.txt
596000 ./from/test2/test.save2.txt
2224000 ./from/test3/test.save3.txt
100 ./from/test3/test.save1.txt
593000 ./from/test3/test.save2.txt
270000 ./from/test4/test.save3.txt
100 ./from/test4/test.save1.txt
332234 ./from/test4/test.save2.txt
2177000 ./from/test4/test.save4.txt
1728000 ./test.save3.txt
180000 ./test.save1.txt
466000 ./test.save11.txt
233000 ./test.save9.txt
686880 ./test.save5.txt
215262 ./test.save7.txt
2560000 ./test.save12.txt
18080 ./test.save10.txt
432000 ./test.save2.txt
10000 ./test.save4.txt
684000 ./test.save6.txt

How do I add up all the individual numbers (using Linux command-line tools)?

Best Answer

This should do it:

find ... -exec cat {} \; | wc -l

If your version of find supports it, this will be much faster:

find ... -exec cat {} + | wc -l

or if you want both the individual counts and the total:

find ... | xargs wc -l

The first two will handle filenames with spaces. In order to make the last one above work if there are filenames with spaces, use -print0 and -0:

find ... -print0 | xargs -0 wc -l