3

Why does the following returning a syntax error:

stringZ=abcABC123ABCabc
echo `expr match "$stringZ" 'abc[A-Z]*.2'`

This works on my ubuntu machine but when I try it on my mac running OS X 10.9.4 I get expr: syntax error?

2
  • Have you tried using echo $(expr match "$stringZ" 'abc[A-Z]*.2')?
    – Tom Fenech
    Commented Aug 30, 2014 at 23:04
  • @TomFenech same issue.
    – rudolph9
    Commented Aug 30, 2014 at 23:07

2 Answers 2

5

This seems like a bash version difference. The : syntax works on my OSX 10.9.4 machine (which has bash 3.2.51, not very current):

echo `expr "$stringZ" : 'abc[A-Z]*.2'`
1
3

expr is quite old-fashioned. On newer bash you may prefer to use the more modern regular expression syntax:

re='abc[A-Z]*.2'
[[ $stringZ =~ $re ]] && echo ${#BASH_REMATCH}

The =~ operator is available since bash version 3.0. For maximum compatibility across older versions of bash, it is recommended to store the pattern to be matched in a separate variable and expand it without quotes. Successful matches are stored in the BASH_REMATCH array. If capturing groups are used, each group will be stored as a separate element in the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.