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 :)
Whenever you use a grep regular expression at the command prompt, surround it with quotes, or escape metacharacters (such as & ! . * $ ? and \ ) with a backslash ( \ ).
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With