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.

Does grep offer a way to count the total number of matches it makes? The -c option only returns the number of lines that matched the regex, but in this case I have multiple matches per line.

share|improve this question

migrated from stackoverflow.com Sep 25 '11 at 2:09

This question came from our site for professional and enthusiast programmers.

2 Answers 2

up vote 22 down vote accepted

try this:

grep -o -E "your expression" file |wc -l

well, -E is just an example, it could be -P, -F etc. point is -o

test:

kent$  echo "abc xxx yyy"|grep -cP "[a-z]{3}"      
1

kent$  echo "abc xxx yyy"|grep -oP "[a-z]{3}"|wc -l
3
share|improve this answer
    
excellent, that worked. –  William Sep 24 '11 at 21:24

There is a -o flag which indicates that only the matched subsection of the line should get printed.

Use that in conjunction with wc -l:

grep -o "part of line" | wc -l

man grep explains it as well.

share|improve this answer

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.