Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .