使用grep时引用?

Ham*_*amy 17 regex quotes grep

Grep的行为不同,取决于我用正则表达式包围的引号.我似乎无法清楚地理解为什么会这样.以下是问题的示例:

hamiltont$ grep -e show\(  test.txt 
  variable.show();
  variable.show(a);
  variable.show(abc, 132);
  variableshow();
hamiltont$ grep -e "show\("  test.txt 
grep: Unmatched ( or \(
hamiltont$ grep -e 'show\('  test.txt 
grep: Unmatched ( or \(
Run Code Online (Sandbox Code Playgroud)

我只是假设有一些正确的方法用单/双引号括起正则表达式.有帮助吗?

FWIW,grep --version返回grep (GNU grep) 2.5.1

小智 25

包含参数的命令行在执行之前由shell处理.您可以使用echo来查看shell的功能:

$ echo grep -e show\(  test.txt 
grep -e show( test.txt

$ echo grep -e "show\("  test.txt 
grep -e show\( test.txt

$ echo grep -e 'show\('  test.txt 
grep -e show\( test.txt
Run Code Online (Sandbox Code Playgroud)

所以不带引号的反斜杠被删除使得"("普通字符的grep(grep所使用的基本默认的正则表达式,使用-E使grep的使用扩展的正则表达式).

  • 我还是不明白单引号和双引号有什么区别。在您发布的示例中,他们似乎做了同样的事情。 (2认同)

Bet*_*eta 5

为了:

grep -e show( test.txt
Run Code Online (Sandbox Code Playgroud)

不起作用,因为外壳将 解释(为特殊的括号,而不仅仅是一个字符,并且找不到结束的).

这些都有效:

grep -e 'show(' test.txt
grep -e "show(" test.txt
Run Code Online (Sandbox Code Playgroud)

因为 shell 将引用的文本视为文本,并将其传递给 grep。

这些不起作用:

grep -e 'show\(' test.txt
grep -e "show\(" test.txt
Run Code Online (Sandbox Code Playgroud)

因为 shell 传递show\(给 grep,grep 将其\(视为特殊的括号,而不仅仅是一个字符,并且找不到结束的\).