Sunday, May 25, 2008

Index of substring - awk

index is a built-in function within awk

index(s1,s2) -- The first location of s2 within s1; 0 if not found


$ s1="Trying to see if is reachable; ping successful"

And substring s2:

$ s2="ping successful"

Now to find the index of s2 in s1:

$ awk -v a="$s1" -v b="$s2" 'BEGIN{print index(a,b)}'

Using index with awk substr function:

We will extract the pattern "ing" from the substring s2 using awk substr function like this:

$ awk -v a="$s1" -v b="$s2" 'BEGIN{print substr(b,2,3)}'

Now we will find the first index where "ing" occurs in parent string s1 like this:

$ awk -v a="$s1" -v b="$s2" 'BEGIN{print index(a,substr(b,2,3))}'


Philluder said...

If you use bash 4,x then you can source an string library written in bash:

Some examples for index operations:
String a abcda
a.indexOf a
a.lastIndexOf a

There are a lot of string methods you can use in your scripts after sourcing the bash file.

Jadu Saikia said...

@Philluder thanks for this great tip.

© Jadu Saikia