31

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.

29

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
| improve this answer | |
8

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.

| improve this answer | |
1

As an alternative to the other answers, using just grep:

grep -o "seach pattern" somefile.txt | grep -c ""

The -o in the first grep outputs each match, and just the match - not the entire line (unless the entire line IS the match, of course). The -c in the second grep then counts 'em.

It's a few more characters to type (like, 4 or 5), but I find it easier to remember.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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