Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep pattern single and double quotes

Is there any difference between enclosing grep patterns in single and double quotes?

grep "abc" file.txt

and

grep 'abc' file.txt

I'm asking since there's no way I could test all possible cases on my own, and I don't want to stumble into a case that I get wrong :)

like image 729
Mika H. Avatar asked Nov 08 '12 05:11

Mika H.


People also ask

Do you use quotes with grep?

Whenever you use a grep regular expression at the command prompt, surround it with quotes, or escape metacharacters (such as & ! . * $ ? and \ ) with a backslash ( \ ).

How do you escape quotes in grep?

If you include special characters in patterns typed on the command line, escape them by enclosing them in single quotation marks to prevent inadvertent misinterpretation by the shell or command interpreter. To match a character that is special to grep –E, put a backslash ( \ ) in front of the character.

How do you grep inverted commas?

grep will show a matching line, so all you have to do is to find the two double-quotes... If you want to extract a word that is within double quotes you can, for example, do... Or use grep -o to only show the matching portion of the line (with a non-greedy regex).


2 Answers

I see a difference if you have special characters :

Ex :

grep "foo$barbase" file.txt

The shell will try to expand the variable $barbase, this is maybe not what you intended to do.

If instead you type

grep 'foo$barbase' file.txt

$bar is taken literally.

Finally, always prefer single quotes by default, it's stronger.

like image 114
Gilles Quenot Avatar answered Oct 11 '22 03:10

Gilles Quenot


  • In double quote, the following characters has special meanings: ‘$’, ‘`’, ‘\’, and, when history expansion is enabled, ‘!’.

    The characters ‘$’ and ‘’ retain their special meaning within double quotes ($ for variables and for executing).

    The special parameters ‘*’ and ‘@’ retain their special meaning in double quotes as inputs when proceeded by $.

    ‘$’, ‘`’, ‘"’, ‘\’, or newline can be escaped by preceding them with a backslash.

    The backslash retains its special meaning when followed by ‘$’, ‘`’, ‘"’, ‘\’, or newline. Backslashes preceding characters without a special meaning are left unmodified.

    Also it will be helpful to check shell expansions:
    https://www.gnu.org/software/bash/manual/html_node/Shell-Expansions.html#Shell-Expansions

  • Single quote ignore shell expansions.
like image 30
Zhenhua Avatar answered Oct 11 '22 03:10

Zhenhua