You can also use the grep command to search for targets defined as patterns 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 and need to be quoted or escaped. Whenever you use a grep regular expression at the command prompt, surround it with quotes, or escape metacharacters (such as & ! . * $ ? and \) with a backslash (\).
A caret (^) indicates the beginning of the line. So the command:
$ grep '^b' list |
finds any line in the file list starting with "b."
A dollar-sign ($) indicates the end of the line. The command:
$ grep 'b$' list |
displays any line in which "b" is the last character on the line. And the command:
$ grep '^b$' list |
displays any line in list where "b" is the only character on the line.
Within a regular expression, dot (.) finds any single character. So the command:
$ grep 'an.' list |
would match any three characters with "an" as the first two, including "any," "and," "management," and "plan" (because spaces count, too).
When an asterisk (*) follows a character, grep interprets it as "zero or more instances of that character." When the asterisk follows a regular expression, grep interprets it as "zero or more instances of characters matching the pattern."
Because it includes zero occurrences, usage of the asterisk is a little non-intuitive. Suppose you want to find all words with the letters "qu" in them. Typing:
$ grep 'qu*' list |
will work as expected. However, if you wanted to find all words containing the letter "n," you would have to type:
$ grep 'nn*' list |
If you wanted to find all words containing the pattern "nn," you would have to type:
$ grep 'nnn*' list |
You may want to try this to see what happens otherwise.
To match zero or more occurrences of any character in list, type:
$ grep .* list |