## 36.22. Testing Characters in a String with expr

The expr (Section 36.21) command does a lot of different things with expressions. One expression it handles has three arguments: first, a string; second, a colon (:); third, a regular expression (Section 32.4). The string and regular expression usually need quotes.

expr can count the number of characters that match the regular expression. The regular expression is automatically anchored to the start of the string you're matching, as if you'd typed a `^` at the start of it in grep, sed, and so on. expr is usually run with backquotes (Section 28.14) to save its output:

>     $ part="resistor 321-1234-00"
>     $ name="Ellen Smith"
>        ...
>     $ expr "$part" : '[a-z ]*[0-9]'        ...character position of first number
>     10
>     $ len=`expr "$name" : '[a-zA-Z]*'`
>     $ echo first name has $len characters
>     first name has 5 characters

When a regular expression matches some character(s), expr returns a zero ("true") exit status (Section 35.12). If you want a true/false test like this, throw away the number that expr prints and test its exit status:

`/dev/null` Section 43.12

>     $ if expr "$part" : '.*[0-9]' > /dev/null
>     > then echo \$part has a number in it.
>     > else echo "it doesn't"
>     > fi
>     $part has a number in it.

-- JP

Copyright © 2003 O'Reilly & Associates. All rights reserved.