28

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?

ealfonso
  • 6,622
  • 5
  • 39
  • 67
YXD
  • 31,741
  • 15
  • 75
  • 115

2 Answers2

35

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\[\(\] *
ephemient
  • 198,619
  • 38
  • 280
  • 391
  • 10
    Or if you don't want to do the escaping of the paren, for Perl, use the -Q flag. `ack -Q 'methodname('` – Andy Lester Feb 28 '11 at 21:49
  • Single quotes are best if you want to search for e.g. PHP variables prefixed with `$`. But then again, single quotes forces you to use ugly escaping if you want to search for strings containing single quotes: http://stackoverflow.com/questions/7254509/how-to-escape-single-quotes-in-bash-grep – Christian Davén Oct 05 '12 at 08:40
  • I never knew about ack-grep - Thanks! – Michael Feb 24 '17 at 07:54
1

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(
$ 
codaddict
  • 445,704
  • 82
  • 492
  • 529