using expr with strings
The expr
expression "$str" : ".*$x"
is a regular expression match. The general form is
expr STRING : REGEXP
where REGEXP
is an anchored regular expression - "anchored" meaning that it attempts to match REGEX
starting from the first character of STRING
, so in order to match $x
anywhere inside $str
you need something like .*
to slurp up all the characters from the anchor to the start of $x
The result is the length of the matched pattern - that includes everything matched by .*
as well as everything matched by $x
. So
expr "$str" : ".*$x" - length "$x"
returns the starting index of the match of $x
in $str
, or minus the length of $x
if no match is found. So for example:
$ expr foobarbaz : ".*bar" - length bar
3
$ expr foobar : ".*baz" - length baz
-3
Note that although you may be "using expr
with strings", it will actually interpret $x
as an (GNU basic) regular expression - so be careful if it contains anything other than alphanumeric characters.