用grep计算匹配总数,而不是只计算匹配的行数

分享于 

分钟阅读

 
点击句子查看译文 显示原文      显示译文      双语对照    源址


Question :

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.


Answer 1 :

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




Answer 2 :

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.



MAT  number  GREP