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
?
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'`
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.
echo $(expr match "$stringZ" 'abc[A-Z]*.2')
?