Grep not as a regular expression

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.

63719 次浏览

Escape the $ by putting a \ in front of it.

使用 fgrep(不推荐)、 grep -Fgrep --fixed-strings,使其将模式视为固定字符串的列表,而不是正则表达式。

For reference, the documentation mentions (excerpts):

将模式解释为固定的列表 strings (instead of regular expressions), separated by newlines, any of which is to be matched. (-F is specified by POSIX.)

fgrepgrep -F相同,直接调用与 fgrep 相同 deprecated, but is provided to allow historical applications that rely 不加修改地运行。

如需完整的参考资料,请检查: Https://www.gnu.org/savannah-checkouts/gnu/grep/manual/grep.html

grep -F是告诉 grep将参数解释为固定字符串而不是模式的标准方法。

您必须告诉 grep 您使用的是固定字符串,而不是模式,使用’-F’:

grep -ir "Something Here" * | grep -F \$somevar

在这个问题中,主要的问题不是关于 grep$解释为正则表达式。它是关于 shell 用环境变量 someVar(可能是空字符串)的值替换 $someVar

所以在第一个例子中,它就像在没有任何参数的情况下调用 grep,这就是为什么它给出 usage输出的原因。第二个示例不应返回包含 someVar的所有行,而应返回所有行,因为空字符串包含在所有行中。

要告诉 shell 不要替换,必须使用 '$someVar'\$someVar。然后您必须处理对 $字符的 grep 解释,因此在许多其他答案中给出了 grep -F选项。

因此,一个有效的答案是:

grep -ir "Something Here" * | grep '$someVar'

对于 -F选项 + 1,它应该是可接受的答案。 另外,我在文件中搜索 -I..模式时有一个“奇怪”的行为,因为 -I被认为是 grep的一个选项; 为了避免这类错误,我们可以使用 --显式地指定命令参数的结尾。

例如:

grep -HnrF -- <pattern> <files>

希望能帮到别人。