Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
add comment

5 Answers

up vote 6 down vote accepted

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 
share|improve this answer
add comment

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

wc -l filename

Example:

wc -l myfile.txt 
share|improve this answer
add comment

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!!!

share|improve this answer
1  
e.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 Mar 21 '11 at 10:53
add comment
$ 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
share|improve this answer
add comment

Untested, but how about something like:

cat `find . -name "searchterm" -print` | wc -l
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.