15

good day all

I am not able to see my error, I would like to find the position of a substring "searchstring" within string "t"

of a few methods I have looked at, this seems easiest and most understandable however this just hangs (both)

awk 'match($t, "$searchstring")'

awk '{print match($t, "$searchstring")}' 

original post - post #3

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

  • searchstring ="IP for"

any suggestions?

3 Answers 3

21

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.

4
  • 1
    thanks, this does exactly what I need, however any idea why the awk expression does not work?
    – CybeX
    Commented Nov 17, 2015 at 21:41
  • 3
    $t is a shell variable, not expanded in single quotes, not accesible to awk.
    – choroba
    Commented Nov 17, 2015 at 22:35
  • What if $searchstring not exist?
    – linrongbin
    Commented Jun 13, 2023 at 1:59
  • @linrongbin: If the $searchstring is not present in the $t, the result will be negative.
    – choroba
    Commented Jun 13, 2023 at 8:41
5

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}
0

How about this?

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

temp=${t%%$searchstring*} && indexOf=$(echo "${t%%$searchstring*}" | cat ${#temp})
echo "$indexOf"

Outputs:

23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .