Michael Mior
Michael Mior

Reputation: 28752

grep with --include and --exclude

I want to search for a string foo within the app directory, but excluding any file which contains migrations in the file name. I expected this grep command to work

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

The above command seems to ignore the --exclude filter. As an alternative, I can do

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

This works, but this loses highlighting of foo in the results. I can also bring find into the mix and keep my highlighting.

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

I'm just wondering if I'm missing something about the combination of command line parameters to grep or if they simply don't work together.

Upvotes: 4

Views: 6144

Answers (2)

felix
felix

Reputation: 486

I was looking for a term on a .py file, but didn't want migration files to be scanned, so what I found (for grep 2.10) was the following (I hope this helps):

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

Upvotes: 3

nullrevolution
nullrevolution

Reputation: 4137

man grep says:

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

because it says "only" there, i'm guessing that your --include statment is overriding your --exclude statement.

Upvotes: 0

Related Questions