Finding the position of a sub string within a strong

James Michael Fultz croooow at gmail.com
Mon Nov 30 03:13:28 UTC 2009


* Ray Parrish <crp at cmc.net> [2009-11-29 13:02 -0800]:
> While reading i found the following method, which seems reasonable to me.
> 
> Position=`expr index "$String" "$SubString"`
> 
> That returns the starting position of SubString within String, and it 
> even works! I'm beginning to see the possibilities as I learn more about 
> bash.

Except it doesn't do that unless you have a very different
implementation of expr than I do here.  It returns the index of the
first matching character of the second argument in the first argument.
The syntax is properly described as 'expr index STRING CHARACTERS'.

$ expr index abczat1256 zat
1

The first matching character being the 'a' at position 1 in the string.

Also, it's notable that 'index' may be a GNU extension to expr since
I did not find it available on NetBSD.

> Thanks for the awk pointer, but this method assigns directly to a 
> variable, which is what I was looking for.

Any command output can be captured in a variable, so you may use AWK or
another program if needed.

Position=`echo "$String" | \
        awk -v SubString=$SubString" '{print index($0,SubString)}'`




More information about the ubuntu-users mailing list