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

Tyilo picture Tyilo · May 31, 2011 · Viewed 24k times · Source

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

Answer

Simon Whitaker picture Simon Whitaker · May 31, 2011

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

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