使用 grep 查找包含引号的字符串

find string including quotation marks using grep

如何使用 grep 查找包含引号的字符串?我尝试使用反斜杠进行转义,但这不起作用。

例如搜索字符串 "localStorage['api']"。 我试过了:

grep -r "localStorage['api']" /path
grep -r "localStorage[\'api\']" /path

你的转义没问题。问题在于 []grep 理解为正则表达式。因此,您需要以某种方式告诉它将该字符串视为文字。为此,我们有 -F:

grep -F "localStorage['api']" file

测试

$ cat a
hello localStorage['api'] and blabla
bye
$ grep -F "localStorage['api']" a
hello localStorage['api'] and blabla

来自man grep

-F, --fixed-strings

Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.