如何在 grep 中避免括号

我想要在一个目录中的所有 JavaScript 文件中搜索函数调用“ init ()”。如何使用 grep 完成此操作?

特别是,我如何避免括号,()

79806 次浏览

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*\)'
$ echo "init()" | grep -Erin 'init\([^)]*\)'
1:init()


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


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

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

grep 'init()' *.js

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.