Regular Expressions   «Prev  Next»
Lesson 3 Using quotes with regular expressions
Objective Identify how quotes affect regular expressions.

Using Quotes with Regular Expressions

When you use grep, you should enclose the regular expression argument in quotes.
You already know that the shell interprets arguments before passing them to a command for execution. When using grep, the regular expression is always the first argument.
All remaining arguments are considered to be file names. For example, suppose you are searching the factsheet file for the pattern barbershop style.
The following SlideShow compares the results depending on the use of quotes.

With quotes, the shell processes the first two words "barbershop style" factsheet
in the barbershop style for
in the barbershop style
Without quotes, the shell sees each word as an argument. The command searches for a single word, barbershop, in two files named style and factsheet. In this case, grep reports an error because it cannot find a file named style, but the grep searches factsheet and displays additional matches.

Enclosing Arguments in Quotes

Multi-word Argument

By placing quotes around a multi-word argument, you prevent the shell from using spaces as argument separators. Similarly, you must quote a regular expression if it contains metacharacters because they also have special meaning to the shell.
In fact, because almost every symbolic character means something to the shell, it is best to get into the habit of enclosing all regular expressions in quotes. Although you do not need quotes around a regular expression that does not contain spaces or symbolic characters, it is safer to use quotes all the time.
In most cases, either double quotes or single quotes will work, as long as they are the same on both sides of the argument.
In the next lesson, you will learn how to use the dot (.), asterisk (*), and brackets ([ ]) to match occurrences of a pattern.