mattalxndr
mattalxndr

Reputation: 9408

Grep: Excluding a specific folder using

Say our folder structure looks like this:

/app
/app/data
...
/app/secondary
/app/secondary/data

I want to recursively search /app/data but I do not want to search /app/secondary/data.

From within the app folder, what would my grep command look like?

Upvotes: 8

Views: 4807

Answers (2)

Alex Yursha
Alex Yursha

Reputation: 3408

Why the accepted answer is wrong

The accepted answer by @seamus is wrong because grep -r --exclude-dir=<glob> matches against base names which by definition can't contain slashes (slashes turn it into a no-op effectively as no base name will match).

From GNU Grep Manual:

--exclude-dir=glob

...When searching recursively, skip any subdirectory whose base name matches glob...

Why the question is probably wrong

I think the OP's directory structure doesn't represent the problem well because because if one has...

.
├── app
    ├── data
    └── secondary
        └── data

... and the current directory is app one can simply do:

> grep -r <search-pattern> data

It will not search the secondary folder as its not inside data.

What the intended question might be

Given directory structure with nested data folders how to look in the top-level data but not in the nested folders.

.
└── data
    ├── file.txt
    ├── folder1
    │   └── folder2
    │       ├── data
    │       │   └── file.txt
    │       └── file.txt
    └── folder3
        ├── data
        │   └── file.txt
        └── file.txt

What the answer would be

> grep -r --exclude-dir='data' <search-pattern> data/*

Note the * at the end. If omitted the top-level data folder won't be searched neither.

Upvotes: 8

seamus
seamus

Reputation: 445

This will do the trick

grep -r --exclude-dir='secondary/data' PATTERN data

Upvotes: 15

Related Questions