字符串搜索:使用find/grep,忽略.git和其他目录

moe*_*oey 5 command-line grep find

我经常需要从具有git目录的目录中搜索特定的字符串.git/.这是我使用的命令:

find . -name .git -prune -o -print | xargs grep <string-to-search>
Run Code Online (Sandbox Code Playgroud)

-name .git -prune -o -print选项是忽略下的文件.git/.但是,它会输出大量"是目录"的消息,这些消息会使整个结果变得混乱.例如,

...
grep: ./reports: Is a directory
grep: ./scripts: Is a directory
grep: ./scripts/js: Is a directory
grep: ./scripts/js/adapter: Is a directory
...
Run Code Online (Sandbox Code Playgroud)

如何修改命令行,以便我可以忽略.git/目录所有其他目录(即只搜索可搜索的文件).

显然,该-type f选项在以下方面效果不佳:

find -type f . -name .git -prune -o -print
Run Code Online (Sandbox Code Playgroud)

Viv*_*oel 17

您不需要find命令.您可以使用grep在目录中搜索.您可以使用exclude-dir语法忽略目录.

grep -r --exclude-dir=".git;.svn" "string to search" <directory>
Run Code Online (Sandbox Code Playgroud)

  • 注意:这需要[GNU Grep(> = 2.5.2)](http://stackoverflow.com/a/8692318/78845). (2认同)
  • 这对我来说不起作用;分隔的路径。如果有任何问题,请尝试单个目录 (2认同)
  • 赞成,因为这在使用 [repo](https://source.android.com/source/downloading.html) 时适用于多个 .git 存储库。但是,我必须像这样拆分 `;` 文件分隔符:`grep -R --exclude-dir=".git" --exclude-dir=".svn" MyRegex` (2认同)