user3667089
user3667089

Reputation: 3278

How to exclude a specific file in find

Suppose my directory structure looks like

A--file1.cpp
   file2.cpp
   file3.cpp
   file1.h
   file2.h
   file3.h

B--file1.cpp
   file2.cpp
   file3.cpp
   file1.h
   file2.h
   file3.h

and my goal is to find every cpp file besides file1.cpp in the A folder

find A/ B/ -name \*.cpp will find all the files, and I tried find A/ B/ ! -name file1.cpp -name \*.cpp this will exclude file1.cpp from the B folder as well. find A/ B/ -prune -o file1.cpp -name \*.cpp doesn't work either. What is the correct way to do it?

Upvotes: 0

Views: 1124

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295279

The -path predicate will let you ignore a specific file or directory.

find . -path ./A/file1.cpp -prune -o -type f -name '*.cpp' -print

Tested as follows:

tempdir=$(mktemp -d "$TMPDIR"/test.d.XXXXXX)
cd "$tempdir" && {
  mkdir -p A B
  touch {A,B}/file{1,2,3}.{cpp,h}
  find A B -path A/file1.cpp -prune -o -type f -name '*.cpp' -print
  rm -rf -- "$tempdir"
}

...emitting output of:

A/file2.cpp
A/file3.cpp
B/file1.cpp
B/file2.cpp
B/file3.cpp

Upvotes: 2

Related Questions