【问题标题】:Find all files contained into directory named查找包含在名为的目录中的所有文件
【发布时间】:2015-06-09 14:27:22
【问题描述】:

我想递归查找包含在名称为“name1”或名称为“name2”的目录中的所有文件

例如:

structure/of/dir/name1/file1.a
structure/of/dir/name1/file2.b
structure/of/dir/name1/file3.c
structure/of/dir/name1/subfolder/file1s.a
structure/of/dir/name1/subfolder/file2s.b
structure/of/dir/name2/file1.a
structure/of/dir/name2/file2.b
structure/of/dir/name2/file3.c
structure/of/dir/name2/subfolder/file1s.a
structure/of/dir/name2/subfolder/file2s.b
structure/of/dir/name3/name1.a ←this should not show up in the result
structure/of/dir/name3/name2.a ←this should not show up in the result

所以当我启动我的魔法命令时,预期的输出应该是这个并且只有这个:

structure/of/dir/name1/file1.a
structure/of/dir/name1/file2.b
structure/of/dir/name1/file3.c
structure/of/dir/name2/file1.a
structure/of/dir/name2/file2.b
structure/of/dir/name2/file3.c

我编写了一些脚本,但它不起作用,因为它在文件中搜索,而不仅仅是文件夹名称:

for entry in $(find $SEARCH_DIR -type f | grep 'name1\|name2');
    do
      echo "FileName: $(basename $entry)"
 done

【问题讨论】:

    标签: linux bash shell command-line find


    【解决方案1】:

    如果您可以使用-regex 选项,请避免使用[^/] 的子文件夹:

    ~$ find . -type f -regex ".*name1/[^/]*" -o -regex ".*name2/[^/]*"
    ./structure/of/dir/name2/file1.a
    ./structure/of/dir/name2/file3.c
    ./structure/of/dir/name2/subfolder
    ./structure/of/dir/name2/file2.b
    ./structure/of/dir/name1/file1.a
    ./structure/of/dir/name1/file3.c
    ./structure/of/dir/name1/file2.b
    

    【讨论】:

      【解决方案2】:

      我会为此使用 -path-prune,因为它是标准的(与特定于 GNU 的 -regex 不同)。

      find . \( -path "*/name1/*" -o -path "*/name2/*" \) -prune -type f -print
      

      但更重要的是,永远不要这样做for file in $(find...)。使用 finds -exec 或 while read 循环,具体取决于您对匹配文件的真正需要。有关如何安全处理 find 的更多信息,请参阅 UsingFindBashFAQ 20

      【讨论】:

      • 是的,问题是,如果您想将文件名存储到变量中,该变量将仅存在于 while 循环中,并且一出来它就是空的。
      • @mattobob,如果你在子shell中运行while循环,是的。有多种解决方法。一种方法是在进程替换中运行 find,例如:while IFS= read -rd '' file; do ...; done < <(find ... -print0)。常见问题 20 涵盖了这一点。
      猜你喜欢
      • 2014-09-04
      • 1970-01-01
      • 2018-10-23
      • 2011-03-04
      • 2021-08-26
      • 2021-11-28
      • 1970-01-01
      • 2016-09-04
      相关资源
      最近更新 更多