Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quotes when using grep?

Tags:

Grep acts differently depending on what kind of quotes I surround the regex with. I can't seem to get a clear understanding of why this is. Here is an example of the problem:

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 \(

I am just assuming there is some proper way to enclose the regex with single/double quotes. Any help?

FWIW, grep --version returns grep (GNU grep) 2.5.1

like image 831
Hamy Avatar asked Jun 09 '10 17:06

Hamy


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 ( \ ). finds any line in the file list starting with "b."

How do you grep special characters?

To match a character that is special to grep –E, put a backslash ( \ ) in front of the character. It is usually simpler to use grep –F when you don't need special pattern matching.

How do you escape a double quote in Linux?

' appearing in double quotes is escaped using a backslash. The backslash preceding the ' !

How do you escape quotes in SED?

2.2.3 Double-Quotes In Sed's specification, s command: The meaning of an unescaped backslash immediately followed by any character other than '&', backslash, a digit, newline, or the delimiter character used for this command, is unspecified.


1 Answers

The command line including the arguments is processed by the shell before it is executed. You can use echo to see what the shell does:

$ 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

So without quotes the backslash gets removed making the "(" a normal character for grep (grep uses basic regex by default, use -E to make grep use extended regex).

like image 61
Florian Diesch Avatar answered Nov 17 '22 07:11

Florian Diesch