Grep not as a regular expression
LinuxGrepLinux Problem Overview
I need to search for a PHP variable $someVar
. However, Grep thinks that I am trying to run a regex and is complaining:
$ grep -ir "Something Here" * | grep $someVar
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.
$ grep -ir "Something Here" * | grep "$someVar"
<<Here it returns all rows with "someVar", not only those with "$someVar">>
I don't see an option for telling grep not to interpret the string as a regex, but to include the $
as just another string character.
Linux Solutions
Solution 1 - Linux
Use fgrep
(deprecated), grep -F
or grep --fixed-strings
, to make it treat the pattern as a list of fixed strings, instead of a regex.
For reference, the documentation mentions (excerpts):
> -F
--fixed-strings
Interpret the pattern as a list of fixed
> strings (instead of regular expressions), separated by newlines, any
> of which is to be matched. (-F is specified by POSIX.)
>
> fgrep
is the same as grep -F
. Direct invocation as fgrep is
> deprecated, but is provided to allow historical applications that rely
> on them to run unmodified.
For the complete reference, check: https://www.gnu.org/savannah-checkouts/gnu/grep/manual/grep.html
Solution 2 - Linux
grep -F
is a standard way to tell grep
to interpret argument as a fixed string, not a pattern.
Solution 3 - Linux
You have to tell grep you use a fixed-string, instead of a pattern, using '-F' :
grep -ir "Something Here" * | grep -F \$somevar
Solution 4 - Linux
In this question, the main issue is not about grep
interpreting $
as a regex. It's about the shell substituting $someVar
with the value of the environment variable someVar
, likely the empty string.
So in the first example, it's like calling grep
without any argument, and that's why it gives you a usage
output. The second example should not return all rows containing someVar
but all lines, because the empty string is in all lines.
To tell the shell to not substitute, you have to use '$someVar'
or \$someVar
. Then you'll have to deal with the grep interpretation of the $
character, hence the grep -F
option given in many other answers.
So one valid answer would be:
grep -ir "Something Here" * | grep '$someVar'
Solution 5 - Linux
+1 for the -F
option, it shall be the accepted answer.
Also, I had a "strange" behaviour while searching for the -I..
pattern in my files, as the -I
was considered as an option of grep
; to avoid such kind of errors, we can explicitly specify the end of the arguments of the command using --
.
Example:
grep -HnrF -- <pattern> <files>
Hope that'll help someone.
Solution 6 - Linux
Escape the $
by putting a \
in front of it.