bash - find string index position of substring

Solution 1:

Use parameter expansion:

t="MULTI: primary virtual IP for xyz/x.x.x.x:44595: 10.0.0.12"
searchstring="IP for"

rest=${t#*$searchstring}
echo $(( ${#t} - ${#rest} - ${#searchstring} ))

$rest contains the part of $t after $searchstring. The starting position of the substring is therefore the length of the whole string minus the length of the $rest minus the length of the $searchstring itself.

Solution 2:

Even better and suitable to more cases (consider '#' versus '##' and having more than one instance of 'IP for') would be to remove from the matching string to the end and use the length of what remains.

text="MULTI: primary virtual IP for xyz/x.x.x.x:44595: 10.0.0.12"
search="IP for"

prefix=${text%%$search*}
echo ${#prefix}