I am using gedit text editor with embedded terminal in ubuntu 12.04. I'm trying to search for some text using grep. I want to search for this line of code

'type' => 'select'

I tried:

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

But grep didn't return any results.

So can someone kindly tell me how to search for the code above?


Surround your search string with double quotes:

grep "'type' => 'select'"
| improve this answer | |

You cannot escape single quotes that appear within single quotes. As explained in the [bash manual]:(http://www.gnu.org/software/bash/manual/bashref.html#Single-Quotes):

Enclosing characters in single quotes (‘'’) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

So, you have to use different approaches:

  1. Use double quotes:

    grep  "'type' => 'select'" file 
  2. If you prefer needlessly complex solutions:

    grep  "'"type"'"\ =\>\ "'"select"'" file 
  3. You can always search for any single character instead of specifying the single quotes:

    grep  '.type. => .select.' file 

But just use ", it makes things much more straightforward.

| improve this answer | |
  • What if the string I'm searching for is in a php file and contains variables? I'm really struggling with this one. – Aubrey Robertson Aug 30 '16 at 23:29
  • @AubreyRobertson I'd need an example to answer properly. If you want to find something like the string $var, you could do grep '$var' file.php in single quotes. For more detail, please post a new question and leave me a comment here. I'd be happy to help. – terdon Aug 31 '16 at 0:05
  • I figured it out. It wasn't the dollar signs that were bungling my grep, it was the array references (square brackets) because grep uses those for regex. This is the line I was trying to grep: $output = $info['function']($variables); I just had to escape them properly with double backslash. This is my grep command after all said and done: targetstring="\$output = \$info\\['function'\\](\$variables);" targetlinenumber=`grep -n "$targetfile" -e "$targetstring" | cut -d :f 1` – Aubrey Robertson Aug 31 '16 at 14:52

cd to the directory that contains your .txt file

cd /path 

Then :

you can use grep "'type' => 'select'" name.txt

or :

`grep "'type' => 'select'" /path/file.txt

Output :

enter image description here

| improve this answer | |
  • 3
    The question only concerns the single quotes, not the directory structure or any of grep's other (slightly irrelevant) functionality. – Chris Mar 10 '14 at 6:09
  • @Chris, indeed, with the -r option (as OP writes), the file name is not necessary. – Brady Trainor Aug 2 '14 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.