如何在一个Git管理的项目中,搜索目录树中文件的内容?

9

我喜欢unix的find命令,但当我想在项目中搜索任意文件夹或子文件夹中的文本时,我总是觉得它太过繁琐。
有没有更简单的方法?

5个回答

10

尝试使用 grep 工具:

  1. 递归搜索目录树中的字符串:

使用:grep -rl alvin .

  1. 搜索多个子目录:

你的递归 grep 搜索不必限于当前目录。下一个示例展示了如何递归地在两个不相关的目录中搜索大小写不敏感的字符串 "alvin":

grep -ril alvin /home/cato /htdocs/zenf
  1. 递归使用egrep:

您还可以使用egrep命令执行递归搜索,它允许您一次搜索多个模式。

egrep -ril 'aja|alvin' .

请注意,在此情况下,需要在搜索模式周围加上引号。

概述: grep -r notes:

关于 grep -r 命令的一些说明:

  • 如果不使用 -l(小写的“L”)标志,这个grep命令没有多大意义。该标志告诉grep打印匹配的文件名。

  • 不要忘记在grep命令的末尾列出一个或多个目录。如果忘记添加任何目录,grep将尝试从标准输入读取(与往常一样)。

  • 如所示,您还可以使用其他正常的grep标志,包括-i以忽略大小写,-v以颠倒搜索的含义等。


3

git grep 是一种方法,但它会忽略未跟踪的文件(所以它不完全等同于您使用 find 的任何操作)。还有其他一些方法可以避免 find 奇怪的语法来实现这一点:

grep -r "<string>" /path/to/repo

你也可以尝试我的个人最爱 grep 替代品,ack, 在我的亲身经历中,它的表现优于 grepgit grep

ack "<string>" /path/to/repo ;# path is unnecessary if you're already in the repo

我安装了ack,但是使用上述命令时只会出现“目录未找到”(或者没有任何输出)。 - Michael Durrant
啊,这是 ack-grep。虽然很有用(+1),但对我来说指令不正确。可能是操作系统的问题。我使用的是 Ubuntu。 - Michael Durrant
啊,很有可能。我正在使用OSX。你用了什么命令?我可以相应地编辑答案。 - Christopher
啊,你使用了CPAN模块还是可执行文件? 看起来这个可执行文件 curl 直接安装到了 ~/bin/ack - Christopher

2

Grep是最简单的方法。

grep -r 'text to find' .

1

git grep "你的文本字符串",从应用程序的基目录开始是一个很好的方法。

正如克里斯托弗所指出的那样,ack也非常有用。

他的安装方法对我没有起作用。我不得不执行以下操作:

sudo apt-get install ack-grep

然后为了方便起见

alias ack='ack-grep '  # So that I can just type ack "string"

我还会将其添加到我的~/.bash_aliases文件中。


你为什么要这样回答自己的问题?! - tuxtimo
回答自己的问题是可以的;这个问题和答案都是有用的。 - ebneter
准确无误地说,我经常被额外的答案所感到谦卑(和愉快的惊喜)...就像克里斯托弗的回答一样! - Michael Durrant

1
如果您担心在大型项目中搜索速度缓慢,可以看一下The Silver Searcher。它非常快。在一个75,000行的项目中运行字符串"TODO"的测试仅需不到10毫秒。
自README摘录:

What's so great about Ag?

  • It is an order of magnitude faster than ack.
  • It ignores file patterns from your .gitignore and .hgignore.
  • If there are files in your source repo you don't want to search, just add their patterns to a .ignore file. (cough *.min.js cough)
  • The command name is 33% shorter than ack, and all keys are on the home row!

Ag is quite stable now. Most changes are new features, minor bug fixes, or performance improvements. It's much faster than Ack in my benchmarks:

ack test_blah ~/code/  104.66s user 4.82s system 99% cpu 1:50.03 total

ag test_blah ~/code/  4.67s user 4.58s system 286% cpu 3.227 total

Ack and Ag found the same results, but Ag was 34x faster (3.2 seconds vs 110 seconds). My ~/code directory is about 8GB. Thanks to git/hg/ignore, Ag only searched 700MB of that.

它可以通过大多数软件包仓库进行安装,例如:

apt-get install silversearcher-ag

查看README获取更多指令。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接