Linux – Counting total number of matches with grep instead of just how many lines match

command linegreplinuxregexunix

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.

Best Answer

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
Related Question