Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 Sep 25 '11 at 2:09

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

up vote 28 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


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

kent$  echo "abc xxx yyy"|grep -oP "[a-z]{3}"|wc -l
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


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.