0

I have a file which contains a list of directories/files that I want to ignore when searching using find. It looks like this:

.git
.vim
config
.vimrc
.bashrc

This list is not exhaustive and can have any number of items. How can I ignore these files/directories when using find.

I've been trying to do find . -type f ! -path ..., but haven't been able to pass dynamic list as argument.

  • @αғsнιη, maybe so but that one (Exclude a list of directories from unix find command) is closed as unclear, so we can't close this one as a duplicate of that one as then it would become unanswerable. – Stéphane Chazelas Apr 3 at 8:54
  • Do you want to ignore any file/dir named like that, or just the ones at the top-level directory? – Stéphane Chazelas Apr 3 at 8:59
  • I want to ignore any file/dir on any subsequent level (not just on level 1). – Ashish Ranjan Apr 3 at 9:09
  • the answer to the dupe isn't able to handle spaces in the filenames from the list. – mosvy Apr 3 at 12:44
0

With find implementations that support -regex with extended regular expressions (-E -regex in BSD, -regextype posix-extended -regex in GNU), you could do:

find . -regextype posix-extended -regex "\./($(
  sed 's@[][\\|^$.*+?{}()]@\\&@g' < list | paste -sd '|' -))" -prune -o \( \
    -type f -print \)

That excludes those file/dirs and any file/subdir within (find doesn't even descend into them thanks to -prune).

If if want to match any file/dir named like that at any level in the directory tree as opposed to only the ones in ., change the \. to .*.

0

There may be better options, but I would define a wrapper function for that:

find_exclude(){
    while read -r ext; do set "$@" \! -name "$ext"; done
    find . -type f "$@"
}
$ find -type f
./config
./.vim
./dir/.git
./list
$ cat list
.vim
.git
config
$ find_exclude <list
./list

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.