Suppose you’re looking for instances of -42 in a file foo.txt. The command
grep -42 foo.txt
won’t work. Instead you’ll get a warning message like the following.
Usage: grep [OPTION]... PATTERN [FILE]... Try 'grep --help' for more information.
Putting single or double quotes around -42 won’t help. The problem is that
grep interprets 42 as a command line option, and
The solution is to put
-e in front of a regular expression containing a dash. That tells
grep that the next token at the command line is a regular expression, not a command line option. So
grep -e -42 foo.txt
You can also use
-e several times to give
grep several regular expressions to search for. For example,
grep -e cat -e dog foo.txt
will search for “cat” and “dog.”
See the previous post for another example of where
grep doesn’t seem to work. By default
grep supports a restricted regular expression syntax and may need to be told to use “extended” regular expressions.