Alex Rivera | Logout

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

Asked 2011-05-30T22:41:45.387
32

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
Edit
Report

1 Answer

1

Maybe below:

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

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

answered 2011-05-30T22:46:47.443

Your Answer