9

I have a find command that I run to find files whose names contain foo.

I want to skip the .git directory. The command below works except it prints an annoying .git any time it skips a .git directory:

find . ( -name .git ) -prune -o -name '*foo*'

How can I prevent the skipped .git directories from printing to the standard output?

Greg Bacon
  • 134,834
  • 32
  • 188
  • 245
Nathan Neff
  • 553
  • 1
  • 6
  • 9

3 Answers3

10

So just for better visibility:

find -name '.git*' -prune -o -name '*foo*' -print

This also omits .gitignore files; note the trailing -print to omit printing, -prune stops descending into it but without -print prints it nevertheless. Twisted C;

eMPee584
  • 1,945
  • 20
  • 20
  • Here's how to find directories: find . -name '.git\*' -prune -o -name '\*foo\*' -maxdepth 4 -type d -print – Lionel Jul 09 '17 at 02:42
4
find . -not -wholename "./.git*" -name "*foo*"

or, more strictly, if you don't want to see .git/ but do want to search in other dirs whose name also begins with .git (.git-foo/bar/...)

find . -not -wholename "./.git" -not -wholename "./.git/*" -name "*foo*"

If your .git/ directories may not always necessarily be located at the top-level of your search directory, you will want to use -not -wholename ".*/.git" and -not -wholename ".*/.git/*".

A bit odder but more efficient because it prunes the whole .git dir:

find . -not \( -wholename "./.git" -prune \) -name "*foo*"
nishanthshanmugham
  • 2,967
  • 1
  • 25
  • 29
0

Try this one:

find . -name '*foo*' | grep -v '\.git'

This will still traverse into the .git directories, but won't display them. Or you can combine with your version:

find . ( -name .git ) -prune -o -name '*foo*' | grep -v '\.git'

You can also do it without grep:

find . ( -name .git ) -prune -printf '' -o -name '*foo*' -print
petersohn
  • 11,292
  • 13
  • 61
  • 98
  • 1
    Okay -- I found that I don't have to put the -printf '' -- I only have to put the -print on the back of the command! For example, this works: find . \( -name .git \) -prune -o -name '*foo*' -print Thanks! – Nathan Neff May 14 '10 at 16:12
  • Using a grep after find is a bad trick for many reasons. Consider using the builtin options in find for filtering – Toni Homedes i Saun Jan 10 '17 at 08:56
  • 1
    As @ToniHomedesiSaun said, using `grep` is a poor solution - not least because the example you give will ignore all files matching the string `.git` - not just directories. The pure `find` is also not specific to directories, so will ignore files named `.git` – Jonathan Barber Nov 29 '19 at 11:21
  • 1
    `find . ( -name .git ) -prune -false -o -name '*foo*'` works for me – Ian Yang May 08 '20 at 09:11