Linux 如何对带有 [] 等特殊字符的字符串进行 grep?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18227567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:32:17  来源:igfitidea点击:

How do I grep for strings with special characters like []?

linuxgrep

提问by user2507818

I am trying to find all the files has text: $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'], I tried to use grep -rl '$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']' ., but later on found []has special meaning as search pattern. So what is the right command for searching text $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']?

我试图找到所有具有 text: 的文件$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'],我尝试使用grep -rl '$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']' .,但后来发现[]作为搜索模式具有特殊含义。那么搜索文本的正确命令是$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']什么?

采纳答案by Maxim Egorushkin

You are right that [and ]are special characters. Quote them with \or use fgrepinstead. The latter is plain string search:

你是正确的,[而且]是特殊字符。用\fgrep代替它们引用它们。后者是纯字符串搜索:

fgrep "$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']" ...

You still need to quote $though because it is otherwise interpreted by bashand other shells.

您仍然需要引用,$因为它会被bash其他 shell以其他方式解释。

回答by Junior Dussouillez

As Maxim Yegorushkin said, you have to escape the $ and [ ] characters.

正如 Maxim Yegorushkin 所说,您必须转义 $ 和 [ ] 字符。

grep -rl "$GLOBALS\['TYPO3_CONF_VARS'\]\['SC_OPTIONS'\]" .

回答by 99 Problems - Syntax ain't one

You can use the -F or --fixed-strings to specify a list of strings to be matched.

您可以使用 -F 或 --fixed-strings 来指定要匹配的字符串列表。

grep -Frl "\$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']" /path/to/files

grep -Frl "\$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']" /path/to/files

From the man page for grep:

从 grep 的手册页:

-F, --fixed-strings Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched. (-F is specified by POSIX .)

-F, --fixed-strings 将 PATTERN 解释为固定字符串列表,以换行符分隔,其中任何一个都将被匹配。(-F 由 POSIX 指定。)

fgrepis deprecated but may be still available as an alternative to grep -F.

fgrep已弃用,但仍可作为grep -F.