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


UNIX in a Nutshell: System V Edition

UNIX in a Nutshell: System V EditionSearch this book
Previous: 5.8 Invoking the Shell Chapter 6 Next: 6.2 Metacharacters, Listed by UNIX Program
 

6. Pattern Matching

A number of UNIX text-editing utilities let you search for, and in some cases change, text patterns rather than fixed strings. These utilities include the editing programs ed, ex, vi, and sed, the awk scripting language, and the commands grep and egrep . Text patterns (also called regular expressions) contain normal characters mixed with special characters (also called metacharacters).

This section presents the following topics:

  • Filenames versus patterns

  • List of metacharacters available to each program

  • Description of metacharacters

  • Examples

6.1 Filenames Versus Patterns

Metacharacters used in pattern matching are different from metacharacters used for filename expansion (see Sections 4 and 5). When you issue a command on the command line, special characters are seen first by the shell, then by the program; therefore, unquoted metacharacters are interpreted by the shell for filename expansion. The command:

$ 

grep [A-Z]* chap[12]

could, for example, be interpreted by the shell as:

$ 

grep Array.c Bug.c Comp.c chap1 chap2

and would then try to find the pattern Array.c in files Bug.c , Comp.c , chap1 , and chap2 . To bypass the shell and pass the special characters to grep , use quotes:

$ 

grep "[A-Z]*" chap[12]

Double quotes suffice in most cases, but single quotes are the safest bet.

(Note also that in pattern matching, ? matches zero or one instance of a regular expression; in filename expansion, ? matches a single character.)


Previous: 5.8 Invoking the Shell UNIX in a Nutshell: System V Edition Next: 6.2 Metacharacters, Listed by UNIX Program
5.8 Invoking the Shell Book Index 6.2 Metacharacters, Listed by UNIX Program

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