The space character in not special in regular expressions (except in perl
-like ones when the x
flag is enabled), so must not be escaped. \
followed by a space yields unspecified results in POSIX regexps.
So you want:
grep 'blah bazz'
If you want to make it more visible, you can use:
grep 'blah[ ]bazz'
More generally you should not put \
is front of characters that are not regular expression operators. Where X
is not a regular expression operator, \X
may very well be, if not now maybe in a future versions. For instance, +
, <
, d
are not basic regular expression operators , but \<
, \+
and \d
are for some grep
implementations.
You may want to use \
followed by a space in:
grep -P '(?x) foo \ bar'
perl -ne 'print if / foo \ bar /x'
To match on foo bar
when the x
flag is on. But even there, you'd rather do:
grep -P '(?x) foo [ ] bar'
To make it more legible. The whole point of the x
flag is to make regexps more legible like:
perl -ne 'print if m{
\d{4} # year
- \d{2} # month
- \d{2} # day
[ ] (foo | bar | baz)}x'
vs
perl -ne'print if/\d{4}-\d{2}-\d{2} (foo|bar|baz)/'
You can't use [ ]
with the xx
flag (in perl 5.26+, not PCRE) though, where spaces are also ignored inside bracket expressions.
See perldoc perlre
for details of perl regular expressions, and man pcrepattern
for the PCRE (perl-compatible regular expressions) ones. Using \Q \E
is another option.
In any case, while space is a special character in the syntax of the shell and not in regular expressions, there are a number of characters that are special in both such as *
, \
, (
, )
, ?
, $
, ^
, [
, ]
, so would need to be escaped for both if meant to be matched literally, preferably with quotes for the shell, and with \
(or [...]
, or \Q...\E
in perl-like ones) for the regexps.
As \
and $
are common in regular expressions, and those characters are still special to the shell inside double quotes, it's a good habit to put regexps in single quotes rather than double quotes. You'd only use double quotes if you needed to expand a shell parameter into the regular expression as in grep "^$var"
or needed to include a '
in the regexp.
To grep
literal strings as opposed to regular expressions, or in other words, to escape every regular expression operators, you can use the -F
(for F
ixed string) option to grep
. For instance:
grep -F 'blah\ bazz'
Would look for lines that contain blah\ bazz
.