使用 grep 搜索带单引号的文本?

new*_*ser 20 gedit command-line grep

我在 ubuntu 12.04 中使用带有嵌入式终端的 gedit 文本编辑器。我正在尝试使用grep. 我想搜索这行代码

'type' => 'select'
Run Code Online (Sandbox Code Playgroud)

我试过:

grep -r '\'type\' => \'select\''

grep没有返回任何结果。

那么有人可以告诉我如何搜索上面的代码吗?

Chr*_*ris 19

用双引号将搜索字符串括起来:

grep "'type' => 'select'"
Run Code Online (Sandbox Code Playgroud)


ter*_*don 11

您无法转义出现在单引号内的单引号。如bash 手册中所述

将字符括在单引号 (''') 中会保留引号内每个字符的字面值。单引号之间不能出现单引号,即使前面有反斜杠

因此,您必须使用不同的方法:

  1. 使用双引号:

     grep  "'type' => 'select'" file 
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如果您更喜欢不必要的复杂解决方案:

     grep  "'"type"'"\ =\>\ "'"select"'" file 
    
    Run Code Online (Sandbox Code Playgroud)
  3. 您始终可以搜索任何单个字符,而不是指定单引号:

     grep  '.type. => .select.' file 
    
    Run Code Online (Sandbox Code Playgroud)

但只要使用",它会让事情变得更加简单。