【问题标题】:How can I grep for text in specific file names under a specific directory structure recursively?如何递归地查找特定目录结构下特定文件名中的文本?
【发布时间】:2016-01-13 20:12:04
【问题描述】:

我有一个目录,还有数千个其他目录,每个目录都包含一致的目录结构以及我想用 grep 查找文本模式的特定文件名。

假设我从我的根目录中启动 grep,目录如下:

/
   /dir1
      /etc
        /net
          /file.properties
   /dir2
      /etc
        /net
          /file.properties

我想在所有目录 dir1、dir2 等中搜索位于路径“*/etc/net/file.properties”下的所有 file.properties 文件中的文本模式

在我指定的路径结构下,在 file.properties 中搜索所有 dir1、dir2...dirN 的模式时,我的 grep 命令会是什么样子?

我现在拥有的是:

grep -r "text here" --include='*/net/etc/file.properties' .

【问题讨论】:

  • 你必须只使用 grep 吗?你不能找到所有 file.properties 文件,然后从该结果集中 grep 吗?

标签: search terminal grep directory pattern-matching


【解决方案1】:

显而易见的答案似乎是grep "text here" */etc/net/file.properties。是否有太多目录无法正常工作? 如果是这样,您也许可以做类似的事情

for dir in *; do
    if [ -f "$dir/net/etc/file.properties" ]; then
        echo "$dir/net/etc/file.properties"
    fi
done | xargs grep "text here"

【讨论】:

  • 这可行,但它不会将 grep 搜索限制为仅在该路径结构下的文件。我知道这一点,因为通过搜索 grep 输出警告,如 ./dir1234/var/log: No such file or directory。
  • 字符串“/var”直到现在还没有出现在这个帖子中。你知道它是从哪里来的吗?
【解决方案2】:

找到 . -名称“文件.properties”| grep "/etc/net/file.properties" | xargs grep "这里的文字"

【讨论】:

    猜你喜欢
    • 2020-01-13
    • 2021-12-14
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多