Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape parenthesis in grep

Tags:

grep

escaping

I want to grep for a function call 'init()' in all JavaScript files in a directory. How do I do this using grep?

Particularly, how do I escape parenthesis, ()?

like image 327
Megha Joshi - GoogleTV DevRel Avatar asked Sep 09 '10 03:09

Megha Joshi - GoogleTV DevRel


People also ask

How do you escape the parentheses?

Since parentheses are also used for capturing and non-capturing groups, we have to escape the opening parenthesis with a backslash.

What characters need to be escaped 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 ( \ ).

Can I use * in grep command?

To search all files in the current directory, use an asterisk instead of a filename at the end of a grep command. The output shows the name of the file with nix and returns the entire line.


2 Answers

It depends. If you use regular grep, you don't escape:

echo '(foo)' | grep '(fo*)' 

You actually have to escape if you want to use the parentheses as grouping.

If you use extended regular expressions, you do escape:

echo '(foo)' | grep -E '\(fo*\)' 
like image 125
Matthew Flaschen Avatar answered Sep 27 '22 21:09

Matthew Flaschen


If you want to search for exactly the string "init()" then use fgrep "init()" or grep -F "init()".

Both of these will do fixed string matching, i.e. will treat the pattern as a plain string to search for and not as a regex. I believe it is also faster than doing a regex search.

like image 33
Dave Kirby Avatar answered Sep 27 '22 22:09

Dave Kirby