I need to build a list of files present in a directory but also pass in a file containing a list of directories to exclude.

I've seen the below suggestion but I've had no luck with it when it comes to the type flag:

find $dir_name $(printf "! -name %s " $(cat $exclude_file))

Is there a way I can do it or will I need to create the entire list and then work through it removing ones that partially match ones in the exclude directory.

  • 4
    What do you mean by "I've had no luck with it when it comes to the type flag"? Can you show the exact command you're running that doesn't work? Apr 10 '17 at 14:26

Given that your exclude_file contains paths, not names, you need to use -path to match its entries. To exclude matching directories’ subdirectories, you also need to -prune them. This should work:

find . -type d \( $(printf -- "-path */%s -o " $(cat "$exclude_file")) -false \) -prune -o -print

If you only want to see files, you can print only files:

find . -type d \( $(printf -- "-path */%s -o " $(cat "$exclude_file")) -false \) -prune -o -type f -print
  • I've edited this answer, you needed -- in-between printf "-path", or you'll get an "Invalid option -p" due to printf trying to parse it.
    – Someguy123
    Oct 9 '18 at 11:17
  • Thanks @Someguy123; I tested with zsh, which doesn’t need --, but bash does indeed. Oct 9 '18 at 11:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.