【问题标题】:String Search: Using find / grep, While Ignoring .git and Other Directories字符串搜索:使用 find / grep,同时忽略 .git 和其他目录
【发布时间】:2013-01-01 09:57:16
【问题描述】:

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

find . -name .git -prune -o -print | xargs grep <string-to-search>

-name .git -prune -o -print 选项是忽略.git/ 下的文件。但是,它会输出很多 'Is a directory' 消息,这些消息会使整个结果变得混乱。例如,

...
grep: ./reports: Is a directory
grep: ./scripts: Is a directory
grep: ./scripts/js: Is a directory
grep: ./scripts/js/adapter: Is a directory
...

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

显然,-type f 选项不适用于:

find -type f . -name .git -prune -o -print

【问题讨论】:

  • 你为什么不用git-grep
  • 另外,最后一个命令应该是find . -type f -name .git -prune -o -print
  • 谢谢,@Johnsyweb。 find . -type f -name .git -prune -o -print 实际上仍然输出目录。
  • 你说得对——使用git-grep:git grep --untracked &lt;string-to-search&gt; 简单得多。让我保持这个问题;我仍然很好奇我们如何使用 grepfind 的组合来做到这一点。
  • 如果你从不同的地方克隆了多个 .git(例如使用repo),git-grep(或其他工具)可以处理这个问题吗?

标签: command-line grep find


【解决方案1】:

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

grep -r --exclude-dir=".git;.svn" "string to search" <directory>

【讨论】:

  • 注:这需要GNU Grep (>= 2.5.2)
  • grep (BSD grep) 2.5.1-FreeBSD 的任何替代方案?谢谢!
  • 找到 . -not -iwholename '.git'
  • 这对我不起作用;分隔的路径。如果您有任何问题,请尝试单个目录
  • 赞成,因为在使用 repo 时,它适用于多个 .git 存储库。但是,我不得不像这样拆分 ; 文件分隔符:grep -R --exclude-dir=".git" --exclude-dir=".svn" MyRegex
【解决方案2】:

在这里回答我自己的问题(不给任何投票等):

由于我实际上是专门在git-tracked 目录中进行搜索,因此git grep 显然是更简单、更适合这项工作的工具。感谢最初提出这个问题的 @Johnsyweb!

我选择了 Vivek 的答案,因为它提供了原始问题中提出的通用 grep 解决方案。

【讨论】:

    【解决方案3】:

    -type f 放错了位置。它在 -prune 之前过滤掉目录,它需要一个目录名称。命令应该是find . -name .git -prune -o -type f -print。如果只想grep关掉目录,可以设置环境变量GREP_OPTIONS='--directories=skip'

    【讨论】:

      【解决方案4】:

      推荐你试试ripgrephttps://github.com/BurntSushi/ripgrep

      ripgrep 是一个面向行的搜索工具,它递归地在当前目录中搜索一个 正则表达式模式。默认情况下,ripgrep 将遵守 gitignore 规则和 自动跳过隐藏文件/目录和二进制文件。

      它比其他工具(我遇到的)更快,对开发人员更友好,包括 grepfind

      【讨论】:

        猜你喜欢
        • 2022-01-02
        • 2012-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-20
        • 2017-02-21
        • 2013-04-11
        • 2021-12-28
        相关资源
        最近更新 更多