Examples of Searching

When used with grep or egrep, regular expressions normally are surrounded by quotes to avoid interpretation by the shell. (If the pattern contains a $, you must use single quotes, as in '$200', or escape the $, as in "\$200“.) When used with ed, vi, sed, and awk, regular expressions usually are surrounded by / (although any delimiter works). Here are some sample patterns:

Pattern What does it match?
bag The string bag.
^bag “bag” at beginning of line or string.
bag$ “bag” at end of line or string.
^bag$ “bag” as the only text on line.
[Bb]ag “Bag” or “bag.”
b[aeiou]g Second character is a vowel.
b[^aeiou]g Second character is not a vowel.
b.g Second character is any character except newline.
^...$ Any line containing exactly three characters.
^\.Any line that begins with a dot.
^\.[a-z][a-z] Same, followed by two lowercase letters (e.g., troff requests).
^\.[a-z]\{2\} Same as previous, grep or sed only.
^[^.] Any line that doesn’t begin with a dot.
bugs* “bug,” “bugs”, “bugss”, etc.
"word"A word in quotes.
"*word"* A word, with or without quotes.
[A-Z][A-Z]* One or more uppercase letters.
[A-Z]+ Same, egrep or awk only.
[A-Z].* An uppercase letter, followed by zero or more characters.
[A-Z]* Zero or more uppercase letters.
[a-zA-Z] Any letter.
[0-9A-Za-z]+ Any alphanumeric sequence.
egrep or awk pattern What does it match?
[567] One of the numbers 5, 6, or 7
five|six|seven One of the words five, six, or seven
80[23]?86 8086, 80286, or 80386

Get Linux in a Nutshell, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.