user2481458 user2481458 - 6 months ago 14
Bash Question

count no of occurences of a substring in a string using bash

its giving count as 2 where as pattern occurred thrice in the string

It is giving count as 2 where as pattern occurred thrice in the string

echo "axxxaaxx" | grep -o "xx" | wc -l
echo "axxxaaxx" | grep -o "xx"

Answer

Using -P will enable PCRE which supports lookarounds:

echo "axxxaaxx" | grep -P '(?<=x)x'

In this case we are using a lookbehind which means that we will match an x which have an x before it. This makes us able to have overlapping matches:

How the regex is "evaluated":

 xxx
^^
|Cursor
Looking for x on this position, since there is nothing this will not match

 xxx
 ^^
 |Cursor
 Looking for x on this position since it's found we got a match

 xxx
  ^^
  |Cursor
  Looking for x on this position since it's found we got a match
Comments