我想以递归方式查找包含在名称为“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
答案 0 :(得分: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
答案 1 :(得分:1)
我会使用-path
和-prune
,因为它是标准的(与GNU特定的-regex
不同)。
find . \( -path "*/name1/*" -o -path "*/name2/*" \) -prune -type f -print
但更重要的是,永远不要for file in $(find...)
。请改用find
s -exec
或while读取循环,具体取决于您对匹配文件的真正需求。有关如何安全处理find
的更多信息,请参阅UsingFind和BashFAQ 20。