How can I grep for this or that (2 things) in a file?
You need to put the expression in quotation marks. The error you are receiving is a result of bash interpretting the (
as a special character.
Also, you need to tell grep to use extended regular expressions.
$ grep -E '(then|there)' x.x
Without extended regular expressions, you have to escape the |
, (
, and )
. Note that we use single quotation marks here. Bash treats backslashes within double quotation marks specially.
$ grep '\(then\|there\)' x.x
The grouping isn't necessary in this case.
$ grep 'then\|there' x.x
It would be necessary for something like this:
$ grep 'the\(n\|re\)' x.x
Just a quick addendum, most flavours have a command called egrep which is just grep with -E. I personally like much better to type
egrep "i(Pod|Pad|Phone)" access.log
Than to use grep -E
The stuff documented under REGULAR EXPRESSIONS in the (or at least, my) man page is actually for extended regexps;
grep understands three different versions of regular expression syntax: “basic,” “extended” and “perl.” In GNU grep, there is no difference in available functionality between basic and extended syntaxes. In other implementations, basic regular expressions are less powerful. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards.
But grep does not use them by default -- you need the -E
switch:
grep "(then|there)" x.x
Because (from the man page again):
Basic vs Extended Regular Expressions
In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, +, {, \|, (, and ).
So you can also use:
grep "then\|there" x.x
Since the parentheses are superfluous in this case.