【问题标题】:Use grep to search for a string in files, include subfolders使用 grep 在文件中搜索字符串,包括子文件夹
【发布时间】:2010-06-21 10:19:15
【问题描述】:

我必须在文件中搜索特定文本,并使用 grep 命令搜索该文本,但它仅在当前文件夹中搜索。我想要的是使用单个 grep 命令我也可以在当前文件夹中搜索特定内容就像在它的所有子文件夹中一样。我该怎么做???

【问题讨论】:

  • 输入grep --help,它会准确告诉你该怎么做。
  • 也试过了,但没有显示任何关于我在寻找什么的信息。

标签: search shell find grep


【解决方案1】:

POSIX grep 不支持递归搜索 - GNU 版本的 grep 支持。

find . -type f -exec grep 'pattern' {} \;

可以在任何符合 POSIX 的 UNIX 上运行。

【讨论】:

  • find . -type f -exec grep 'pattern' {} /dev/null \; 是我在这里学到的一个重要提示,用于在使用 POSIX grep 的匹配行之前打印文件的名称。
【解决方案2】:

man grep

   -R, -r, --recursive
          Read all  files  under  each  directory,  recursively;  this  is
          equivalent to the -d recurse option.

【讨论】:

  • 我只是在尝试这个,但它没有在子目录中搜索
【解决方案3】:

更常见的是将 find 与 xargs 一起使用,比如

 find <dir> -type f -name <shellglob> -print0 | xargs grep -0 

-print0-0, 分别使用空字符来分隔条目,以避免文件名包含空格字符的问题。

【讨论】:

    猜你喜欢
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    相关资源
    最近更新 更多