I'm trying to exclude all hidden directories from recursive search.

I think .*/\..* this should match hidden directories and this indeed works with find, however grep doesn't think so.

pcregrep -rnI -C 5 --exclude-dir='.*/\..*' '^\s*async def' .

grep -rnIP -C 5 --exclude-dir=*/.* '^\s*def' .

What am I doing wrong here?

Oh, and I know about ripgrep, silver searcher etc. The question is about grep and pcregrep.

  • 1
    Possible duplicate of Exclude hidden subdirectories from grep -r – AJefferiss Mar 2 '17 at 8:55
  • @AJefferiss Yeah I've seen this answer. It's not a duplicate. The answer in the linked question is .* which would exclude current directory which starts with . and wouldn't find anything. – user1685095 Mar 2 '17 at 9:03

With pcregrep:

pcregrep -r --exclude-dir='^\..' pattern .

With grep:

grep -r --exclude-dir='.[^.]*' pattern .

Please note that the meaning of --exclude-dir is different for pcregrep and grep. Read the corresponding manuals for details.

  • Worth noting that grep -r --exclude-dir='.*' pattern works fine too - that is, using '.*' as exclude pattern and omitting the . argument – don_crissti Mar 2 '17 at 11:57
  • @don_crissti Oh, I didn't know about ommiting directory, thanks. I've solved it with $(pwd) but this is better – user1685095 Mar 2 '17 at 12:05
  • @user1685095 - no problem, it's really easy to overlook: "if no file operand is given, grep searches the working directory" - keep in mind though that Sato's solution is the proper way to do it and the only way to make it work if you want to use grep -r on a list of directories which includes . (that is the cwd) – don_crissti Mar 2 '17 at 12:06
  • @don_crissti Also IIRC grep-ing in the current directory when you don't specify a starting point is a GNU extension. – Satō Katsura Mar 2 '17 at 15:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.