z/OS UNIX System Services User's Guide
Previous topic | Next topic | Contents | Contact z/OS | Library | PDF


Patterns

z/OS UNIX System Services User's Guide
SA23-2279-00

The examples of grep, so far, have displayed the records in a file that contain the desired string anywhere in the line. If you want to be more specific—say to find records that begin with a certain string of characters (instead of having that string anywhere in the line)—use grep with patterns instead of strings.

To understand patterns, it helps to think about the special wildcard characters discussed in Using a wildcard character to specify file names. Remember that you can use patterns in commands; for example:
rm *.txt
removes all files in the working directory that have the .txt extension. Instead of specifying a single file name, this example uses the special character * to represent any file name of the appropriate form.
In the same way, a grep pattern uses special characters so that one pattern can represent many different strings.
Note: The special characters for grep patterns are not the same as the characters used on command lines, and the mechanisms involved are also different: however, patterns and wildcard characters are conceptually similar.
Special characters used in a pattern are called pattern characters, or metacharacters. Some pattern characters are:
^ (caret)
Stands for the beginning of a line. For example, ^abc is a pattern that represents abc at the beginning of a line.
$ (dollar sign)
Stands for the end of a line. For example, xyz$ is a pattern that represents xyz at the end of a line.
. (dot or period)
Stands for any (single) character. For example, a.c is a pattern that represents a, followed by any character, followed by c.
* (asterisk)
Indicates zero or more repetitions of part of a pattern. For example, .* indicates zero or more repetitions of . (period). Since the . stands for any character, .* stands for any number of characters. For example, ^a.*z$ is a pattern that represents a at the beginning of a line, z at the end, and any number of characters in between.
A typical grep command has the form:
grep 'pattern' file
This displays all the records in the file that match the given pattern. For example:
grep '^Superman' comics.lst
displays all the records that begin with the word Superman.
grep '00$' comics.lst
displays all the records that end in 00.

If you want to use the literal meaning of a pattern character instead of its special meaning, put a backslash (\) in front of the character.

Example: To find all the lines that end in $1.00, issue:
grep '\$1\.00$' comics.lst
Without a backslash in front of the $ and . (period), these characters would have their special pattern meanings.

Go to the previous page Go to the next page




Copyright IBM Corporation 1990, 2014