Using Awk in shell script to extract an index of a substring from a parent string

Hi All,

I am new to this shell scripting world. Struck up with a problem, can anyone of you please pull me out of this.

Requirement : Need to get the index of a substring from a parent string
Eg : index("Sandy","dy") should return 4 or 3.

My Approach :

I used Awk function index to achieve this

when i excecute this in command line
awk 'BEGIN { print index("Attempting to connect to ipaddr: 127.0.0.1 IllegalUrl_110707092804.txt Succeeded with no errors.","Succeeded with no errors") }'
72

if gives me correct output which is 72

but in shell script it always returns 0.

$a="Attempting to connect to ipaddr: 127.0.0.1 IllegalUrl_110707092804.txt Succeeded with no errors."

$b="Succeeded with no errors"

echo "`awk 'BEGIN { print index($a,$b) }'` "

Can anybody please tell what is the problem or suggest an alternate approach.

Many Thanks,

Sandeep

% a="Attempting to connect to ipaddr: 127.0.0.1 IllegalUrl_110707092804.txt Succeeded with no errors."
% b="Succeeded with no errors"
% awk -v a="$a" -v b="$b" 'BEGIN{print index(a,b)}'
72

Use nawk or /usr/xpg4/bin/awk on Solaris.

Hey Radoulov,

Thanks a lot :slight_smile:

Thanks,
Sandeep