How to count total number of lines of found files?

10

2

I'm running a find . -name pattern to find some files, and I'd like to elegantly get the total number of lines in these files.

How can I achieve that?

GJ.

Posted 2011-03-20T17:46:57.437

Reputation: 8 151

Answers

9

If your version of wc and find support the necessary options:

find . -name pattern -print0 | wc -l --files0-from=-

which will give you per-file counts as well as a total. If you want only the total:

find . -name pattern -print0 | wc -l --files0-from=- | tail -n 1

Another option for versions of find that support it:

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

Paused until further notice.

Posted 2011-03-20T17:46:57.437

Reputation: 86 075

2

$ find . -name '*.txt' -exec cat '{}' \; | wc -l

Takes each file and cats it, then pipes all that through wc set to line counting mode.

Or, [untested] strange filename safe:

$ find . -name '*.txt' -print0 | xargs -0 cat | wc -l

Majenko

Posted 2011-03-20T17:46:57.437

Reputation: 29 007

1

Unfortunately the output of :

find . -iname "yourpattern" -exec cat '{}' \; |wc -l

inserts extra lines. In order to get a reliable line count you should do:

find . -name "yourpattern" -print0 | xargs -0 wc -l

This way you handle spaces correctly, get a line count for each file, and the total line count, faster and in style!!!

g24l

Posted 2011-03-20T17:46:57.437

Reputation: 829

1e.g. : time find . -name ".m" -exec cat '{}' ; | wc -l runs in 4.878s and returns 227847 as line count . But time find . -name ".m" -print0 | xargs -0 wc -l runs in 0.769s and returns the proper line count 126464 . – g24l – 2011-03-21T10:53:22.157

1

Another easy way to find no. lines in a file:

wc -l filename

Example:

wc -l myfile.txt 

vkGunasekaran

Posted 2011-03-20T17:46:57.437

Reputation: 153

-1

Untested, but how about something like:

cat `find . -name "searchterm" -print` | wc -l

Michael Schubert

Posted 2011-03-20T17:46:57.437

Reputation: 540

This will not work well with paths containing spaces or characters that trigger globbing. – Kamil Maciorowski – 2019-08-06T20:09:17.333

-2

wc -l `find -name filename`

will work efficiently.

Mahesh U

Posted 2011-03-20T17:46:57.437

Reputation: 1

… or not, if paths contain spaces or characters that trigger globbing. – Kamil Maciorowski – 2019-08-06T20:06:04.413

And even if it works, this reports the number of lines *in each file,* which is not an elegant way to get the total (as requested). – Scott – 2019-08-07T05:04:54.713