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


Suppose:


$ s1="Trying to see if 172.22.23.12 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)}'
45


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)}'
ing


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))}'
4

6 comments:

Philluder said...

If you use bash 4,x then you can source an string library written in bash:
http://sourceforge.net/projects/oobash/

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

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.

Karan Bohra said...
This comment has been removed by the author.
Karan Bohra said...
This comment has been removed by the author.
Karan Bohra said...

match=${s1%%*$s2*}
${match:+:} eval "idx=$(expr "x${s1%$s2*}" : '.*')"
echo "${idx-0}"

Karan Bohra said...


Provided your IFS does not comprise colon the below can function as an index() func

s1="Trying to see if 172.22.23.12 is reachable; ping successful dee doo"
s2="ping successful"
match=${s1%%*"$s2"*}
${match:+:} eval "idx='$(expr "x${s1%"$s2"*}" : '.*')'"
echo "${idx-0}"

© Jadu Saikia www.UNIXCL.com