开发者

Get total number of matches for a regex via standard unix command

Let's say that I want to count the number of "o" characters in the text

oooasdfa
oasoasgo

My first thought was to do grep -c o, but this returns 2, because grep returns the number of matching lines, not the total number of matches. Is there a flag I can use with grep to change this? Or perhaps I should be using awk开发者_StackOverflow中文版, or some other command?


This will print the number of matches:

echo "oooasdfa
oasoasgo" | grep -o o | wc -l


you can use the shell (bash)

$ var=$(<file)
$ echo $var
oooasdfa oasoasgo
$ o="${var//[^o]/}"
$ echo ${#o}
6

awk

$ awk '{m=gsub("o","");sum+=m}END{print sum}' file
6
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜