Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping a parenthesis in grep/ack

Tags:

regex

grep

ack

I want to look for the string "methodname(", but I am unable to escape the "(". How can I get

grep methodname( *

or

ack-grep methodname( *

to work?

like image 695
YXD Avatar asked Jan 21 '11 16:01

YXD


People also ask

How do you escape characters in grep?

These special characters, called metacharacters, also have special meaning to the system and need to be quoted or escaped. Whenever you use a grep regular expression at the command prompt, surround it with quotes, or escape metacharacters (such as & ! . * $ ? and \ ) with a backslash ( \ ).

Do I need to escape 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.

Is ACK better than grep?

If you're searching binary files, then you must use grep because ack will ignore them, always. When searching through a few large files, grep will be faster than ack.


2 Answers

There's two things interpreting the (: the shell, and ack-grep.

You can use '', "", or \ to escape the ( from the shell, e.g.

grep 'methodname(' *
grep "methodname(" *
grep methodname\( *

grep uses a basic regular expression language by default, so ( isn't special. (It would be if you used egrep or grep -E or grep -P.)

On the other hand, ack-grep takes Perl regular expressions as input, in which ( is also special, so you'll have to escape that too.

ack-grep 'methodname\(' *
ack-grep "methodname\\(" *
ack-grep methodname\\\( *
ack-grep 'methodname[(]' *
ack-grep "methodname[(]" *
ack-grep methodname\[\(\] *
like image 168
ephemient Avatar answered Oct 11 '22 10:10

ephemient


Try adding a \ before the (.

Small demo:

$ cat file
bar
methodname(
foo
$ grep -n methodname\( file
2:methodname(
$ 

Enclosing the pattern in single or double quotes also works:

$ grep -n 'methodname(' file
2:methodname(
$ grep -n "methodname(" file
2:methodname(
$ 
like image 32
codaddict Avatar answered Oct 11 '22 09:10

codaddict