Counting regex pattern matches in one line using s

2020-05-24 20:21发布

问题:

I want to count the number of matches there is on one single line (or all lines as there always will be only one line).

I want to count not just one match per line as in

echo "123 123 123" | grep -c -E "123" # Result: 1

Better example:

echo "1 1 2 2 2 5" | grep -c -E '([^ ])( \1){1}' # Result: 1, expected: 2 or 3

回答1:

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

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


回答2:

Maybe below:

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

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



回答3:

Maybe you should convert spaces to newlines first:

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


回答4:

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.



回答5:

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 '$='