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.

link|improve this question

feedback

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

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

2 Answers

up vote 5 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
link|improve this answer
excellent, that worked. – William Sep 24 '11 at 21:24
feedback

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.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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