Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 823
Tyilo Avatar asked May 30 '11 22:05

Tyilo


People also ask

Can you use regex with grep?

GNU grep supports three regular expression syntaxes, Basic, Extended, and Perl-compatible. In its simplest form, when no regular expression type is given, grep interpret search patterns as basic regular expressions. To interpret the pattern as an extended regular expression, use the -E ( or --extended-regexp ) option.

Can you count with regex?

To count a regex pattern multiple times in a given string, use the method len(re. findall(pattern, string)) that returns the number of matching substrings or len([*re. finditer(pattern, text)]) that unpacks all matching substrings into a list and returns the length of it as well.

How do you grep a pattern?

To find a pattern that is more than one word long, enclose the string with single or double quotation marks. The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.

How do I match a pattern in regex?

Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .


2 Answers

Maybe below:

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

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

like image 28
manojlds Avatar answered Sep 30 '22 12:09

manojlds


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

$ echo "123 123 123" | grep -o 123 | wc -l 3 
like image 73
Simon Whitaker Avatar answered Sep 30 '22 11:09

Simon Whitaker