简体   繁体   中英

Find all files contained into directory named

I would like to recursively find all files contained into a directory that has name “name1” or name “name2”

for instance:

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

so when I start my magic command the expected output should be this and only this:

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

I scripted something but it does not work because it search within the files and not only folder names:

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

If you can use the -regex option, avoiding subfolders with [^/] :

~$ 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

I'd use -path and -prune for this, since it's standard (unlike -regex which is GNU specific).

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

But more importantly, never do for file in $(find...) . Use find s -exec or a while read loop instead, depending on what you really need to with the matching files. See UsingFind and BashFAQ 20 for more on how to handle find safely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM