Counting regex pattern matches in one line using sed or grep?

十年热恋 提交于 2019-12-03 05:23:55

You could use grep -o then pipe through wc -l:

$ echo "123 123 123" | grep -o 123 | wc -l
3

Maybe you should convert spaces to newlines first:

$ echo "1 1 2 2 2 5" | tr ' ' $'\n' | grep -c 2
3

Maybe below:

echo "123 123 123" | sed "s/123 /123\n/g" | wc -l

( maybe ugly, but my bash fu is not that great )

Why not use awk? You could use awk '{print gsub(your_regex,"&")}' to print the number of matches on each line, or awk '{c+=gsub(your_regex,"&")}END{print c}' to print the total number of matches. Note that relative speed may vary depending on which awk implementation is used, and which input is given.

This might work for you:

sed -n -e ':a' -e 's/123//p' -e 'ta' file | sed -n '$='

GNU sed could be written:

sed -n ':;s/123//p;t' file | sed -n '$='
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!