Find all files contained into directory named

96 views Asked by At

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
2

There are 2 answers

0
fredtantini On BEST ANSWER

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
2
geirha On

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 finds -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.