Grep with --include and --exclude

I want to find the string foo in the app directory, but excluding any file containing migrations in the file name. I expected this grep to work

 grep -Ir --include "*.py" --exclude "*migrations*" foo app/ 

The above command ignores the --exclude filter. Alternatively I can do

 grep -Ir --include "*.py" foo app/ | grep -v migrations 

This works, but it loses highlight foo in the results. I can also bring find to the mix and save the selection.

 find app/ -name "*.py" -print0 | xargs -0 grep --exclude "*migrations*" foo 

I'm just wondering if I'm missing something about combining command line options with grep or if they just don't work together.

+4
source share
2 answers

I searched the term in a .py file, but did not want the migration files to be scanned, so I found (for grep 2.10) the following (hope this helps):

 grep -nR --include="*.py" --exclude-dir=migrations whatever_you_are_looking_for . 
+2
source

man grep says:

  --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). 

because it says only, I assume that your --include status overrides your --exclude .

0
source

All Articles