Unix Power ToolsUnix Power ToolsSearch this book

35.11. Pattern Matching in case Statements

A case statement (Section 35.10) is good at string pattern matching. Its "wildcard" pattern-matching metacharacters work like the filename wildcards (Section 1.13) in the shell, with a few twists. Here are some examples:

?)
Matches a string with exactly one character like a, 3, !, and so on.

?*)
Matches a string with one or more characters (a nonempty string).

[yY]|[yY][eE][sS])
Matches y, Y or yes, YES, YeS, etc. The | means "or."

/*/*[0-9])
Matches a file pathname, like /xxx/yyy/somedir/file2, that starts with a slash, contains at least one more slash, and ends with a digit.

'What now?')
Matches the pattern What now?. The quotes (Section 27.12) tell the shell to treat the string literally: not to break it at the space and not to treat the ? as a wildcard.

"$msgs")
Matches the contents of the msgs variable. The double quotes let the shell substitute the variable's value; the quotes also protect spaces and other special characters from the shell. For example, if msgs contains first next, this would match the same string, first next.

To clarify: in bash, for example, the case statement uses the same pathname expansion rules it uses elsewhere in the shell, to determine how to expand the value. In other shells, such as ksh, there are minor differences (such as a relaxation of special treatment for . and / characters). See the manual page for your shell if you have any questions or concerns about what rules your shell will follow.

--JP and SJC



Library Navigation Links

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