简体   繁体   中英

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.

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

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

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

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

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'

+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.

通过在它前面放一个\\来逃避$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM