tags:

views:

43

answers:

4

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 to escape braces ().

A: 

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 parens as grouping

If you use extended regular expressions, you do escape:

echo '(foo)'|grep -E '\(fo*\)'
Matthew Flaschen
When I use grep -rin init() * in the directory it complains syntax error near unexpected token (. How do I fix this.
Megha Joshi
I am sorry, I do not understand. I have a few javascript files, with a init() function called in few places in them. I want to find out where all init() is called, using grep -rin init() * in the directory..It complains about invalid syntax near (. How do I escape ( .
Megha Joshi
@Megha, just to clarify, that was a shell error because you didn't quote the regex.
Matthew Flaschen
+1  A: 
$ echo "init()" | grep -Erin 'init\([^)]*\)'
1:init()

$ echo "init(test)" | grep -Erin 'init\([^)]*\)'
1:init(test)

$ echo "initwhat" | grep -Erin 'init\([^)]*\)'
ghostdog74
This is incorrect. It will just as easily match "initwhatever", since by default backslashed parens create capturing groups. As I said above, you do not escape parens with regular grep.
Matthew Flaschen
+1  A: 

Move to your root directory(if you are aware where the js files are). then do the following

grep 'init()' *.js

Konark Modi
+3  A: 

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.

Dave Kirby