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
2010-09-09 03:37:24
When I use grep -rin init() * in the directory it complains syntax error near unexpected token (. How do I fix this.
Megha Joshi
2010-09-09 03:40:25
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
2010-09-09 03:41:48
@Megha, just to clarify, that was a shell error because you didn't quote the regex.
Matthew Flaschen
2010-09-09 04:47:00
+1
A:
$ echo "init()" | grep -Erin 'init\([^)]*\)'
1:init()
$ echo "init(test)" | grep -Erin 'init\([^)]*\)'
1:init(test)
$ echo "initwhat" | grep -Erin 'init\([^)]*\)'
ghostdog74
2010-09-09 03:52:49
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
2010-09-09 04:45:32
+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
2010-09-09 09:33:53
+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
2010-09-09 09:55:39