2

I would like to get all the files from a directory which have a pattern and are not in a .ignore file.

I've tried this command :

 find . -name '*.js' | grep -Fxv .ignore 

but find output is like ./directory/file.js and the format in my .ignore is the following:

*.min.js directory/directory2/* directory/file_56.js 

So grep does not match any...

Does anyone has an idea/clue of how to do this?

Update So i've found some things but it's not completely working:

find . -name '*.js' -type f $(printf "! -name %s " $(cat .ignore | sed 's/\//\\/g')) | # keeps the path sed 's/^\.\///' | # deleting './' grep -Fxvf .ignore 

It works (not showing) for *.min.js and directory/file_56.js but not for directory/directory2/*

2
  • Try to replace find . -name with find $PWD -name to see if goes better Commented Jan 12, 2017 at 17:17
  • 1
    If this were actually .gitignore, you'd have better tools available, in terms of being able to ask git to do the work for you. Commented Jan 12, 2017 at 23:36

1 Answer 1

2

It looks like you're looking for a subset of the functionality supported by Git's .gitignore file:

args=() while read -r pattern; do [[ ${#args[@]} -gt 0 ]] && args+=( '-o' ) [[ $pattern == */* ]] && args+=( -path "./$pattern" ) || args+=( -name "$pattern" ) done < .ignore find . -name '*.js' ! \( "${args[@]}" \) 

The exclusion tests for find are built up in a Bash array first, which allows applying line-specific logic:

Note how a -path or -name test is used, depending on whether the pattern at hand from .ignore contains at least one / or not:

  • Patterns for -path tests are prefixed with ./ to match the paths output by find.
  • Patterns for -name are left as-is; patterns for *.min.js will match anywhere in the subtree.

With your sample .ignore file, the above results in the following find command:

find . -name '*.js' ! \( \ -name '*.min.js' -o -path './directory/directory2/*' -o -path './directory/file_56.js' \ \) 
Sign up to request clarification or add additional context in comments.

1 Comment

This was exactly the solution i had in mind to implement before to right my answer.... But i could not implement it as nice as you. Good Trick, +1 from me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.