查找包含在名为的目录中的所有文件

Find all files contained into directory named

我想以递归方式查找名称为“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

如果可以使用 -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

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

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

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