如何递归执行grep并排除一级子目录下的指定二级子目录?
Great question—dealing with tons of first-level subdirectories makes manual exclusion totally impractical, so let’s fix this with a smarter grep pattern. Here’s exactly how to skip all /idc and /otherStuffIdc sub-subdirectories, no matter which first-level folder they live under:
The Command You Need
Use wildcard patterns in the --exclude-dir option to target any parent directory followed by your unwanted sub-subdirectories:
grep -r "searchTerm" --exclude-dir='*/idc' --exclude-dir='*/otherStuffIdc' .
If you prefer combining the exclusions into a single flag (just make sure there are no spaces inside the curly braces):
grep -r "searchTerm" --exclude-dir={*/idc,*/otherStuffIdc} .
How This Works
- The
*/wildcard matches any first-level subdirectory (likesubdir1,subdir2, etc.) in your root search folder. - Adding
idcorotherStuffIdcafter the wildcard tells grep to skip any directory that ends with/idcor/otherStuffIdc—which perfectly targets those sub-subdirectories under every first-level folder you have.
Quick Example to Verify
If your directory structure looks like this:
/folder/ ├─ subdir1/ │ ├─ idc/ │ ├─ files/ │ └─ otherStuffIdc/ ├─ subdir2/ │ ├─ idc/ │ └─ files/ └─ ... (many more first-level subdirs)
The command will skip subdir1/idc, subdir1/otherStuffIdc, subdir2/idc, and all identical sub-subdirectories under every other first-level folder—while still searching through the files/ directories and any other valid folders you care about.
内容的提问来源于stack exchange,提问作者Steve

