home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 45.28 Quick Reference: expr Chapter 45
Shell Programming for the Initiated
Next: 45.30 Grabbing Parts of a String

45.29 Testing Characters in a String with expr

The expr ( 45.28 ) 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 ( 26.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 ( 9.16 ) to save its output:


part="resistor 321-1234-00"  name="Ellen Smith"


expr "$part" : '[a-z ]*[0-9]'  

...character position of first number


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 ( 44.7 ) . If you want a true/false test like this, throw away the number that expr prints and test its exit status:



if expr "$part" : '.*[0-9]' > /dev/null


then echo \$part has a number in it.


else echo "it doesn't"



$part has a number in it.

- JP

Previous: 45.28 Quick Reference: expr UNIX Power Tools Next: 45.30 Grabbing Parts of a String
45.28 Quick Reference: expr Book Index 45.30 Grabbing Parts of a String

The UNIX CD Bookshelf Navigation The UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System