You can also use the grep command to search for targets that are defined as patterns by using regular expressions. Regular expressions consist of letters and numbers, in addition to characters with special meaning to grep. These special characters, called metacharacters, also have special meaning to the system. When you use regular expressions with the grep command, you need to tell your system to ignore the special meaning of these metacharacters by escaping them. When you use a grep regular expression at the command prompt, surround the regular expression with quotes. Escape metacharacters (such as & ! . * $ ? and \) with a backslash (\). See Searching for Metacharacters for more information on escaping metacharacters.
A caret (^) metacharacter indicates the beginning of the line. The following command finds any line in the file list that starts with the letter b.
$ grep '^b' list |
A dollar-sign ($) metacharacter indicates the end of the line. The following command displays any line in which b is the last character on the line.
$ grep 'b$' list |
The following command displays any line in the file list where b is the only character on the line.
$ grep '^b$' list |
Within a regular expression, dot (.) finds any single character. The following command matches any three-character string with “an” as the first two characters, including “any,” “and,” “management,” and “plan” (because spaces count, too).
$ grep 'an.' list |
When an asterisk (*) follows a character, grep interprets the asterisk as “zero or more instances of that character.” When the asterisk follows a regular expression, grep interprets the asterisk as “zero or more instances of characters matching the pattern.”
Because it includes zero occurrences, the asterisk can create a confusing command output. If you want to find all words with the letters “qu” in them, type the following command.
$ grep 'qu*' list |
However, if you want to find all words containing the letter “n,” type the following command.
$ grep 'nn*' list |
If you want to find all words containing the pattern “nn,” type the following command.
$ grep 'nnn*' list |
To match zero or more occurrences of any character in list, type the following command.
$ grep .* list |