88

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, ()?

Randall
  • 2,859
  • 1
  • 21
  • 24

4 Answers4

83

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*\)'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • 2
    When I use grep -rin init() * in the directory it complains syntax error near unexpected token (. How do I fix this. – Megha Joshi - GoogleTV DevRel Sep 09 '10 at 03:40
  • 1
    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 - GoogleTV DevRel Sep 09 '10 at 03:41
  • 5
    @Megha, just to clarify, that was a shell error because you didn't quote the regex. – Matthew Flaschen Sep 09 '10 at 04:47
  • 2
    My issue was that I did `grep "{"` instead of `grep '{'`. Double quotes and single quotes makes a big difference for special characters for grep. – Marcus Jun 25 '14 at 17:38
  • 5
    @Marcus Grep doesn't care (or know) whether you used double or single quotes. It's your shell that [parses the quotes](http://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash). – Shriken Jul 30 '15 at 17:38
29

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
  • 25,806
  • 5
  • 67
  • 84
4
$ echo "init()" | grep -Erin 'init\([^)]*\)'
1:init()

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

$ echo "initwhat" | grep -Erin 'init\([^)]*\)'
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • 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 Sep 09 '10 at 04:45
  • I believe this is fine because the '-E' is equivalent to egrep. – gkanwar Feb 19 '14 at 07:03
2

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

grep 'init()' *.js
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Konark Modi
  • 739
  • 6
  • 8