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?

rudolph9
  • 8,021
  • 9
  • 50
  • 80

2 Answers2

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'`
Wm Annis
  • 123
  • 4
  • 1
    Online documentation: https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/expr.1.html – glenn jackman Aug 30 '14 at 23:11
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.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141