Ripgrep, which is a fast alternative to grep, has just introduced the --count-matches
flag allowing counting each match in version 0.9 (I'm using the above example to stay consistent):
> echo afoobarfoobar | rg --count foo
1
> echo afoobarfoobar | rg --count-matches foo
2
As asked by OP, ripgrep allows for regex pattern as well (--regexp <PATTERN>
).
Also it can print each (line) match on a separate line:
> echo -e "line1foo\nline2afoobarfoobar" | rg foo
line1foo
line2afoobarfoobar