I have a whole repository of files and I am trying to get a list of files that match a certain criteria.

For example, let us say that I want to take all the files that have the string foo1 and foo2/foo3 in the path and do not have bar1 or bar2/bar3. Note that it is possible for bar1 or bar2/bar3 to be a sub directory of foo* and in that case those directories should also be excluded. I tried the following method:


find . -name '*'.cpp | grep $IN_REGEX | grep -v $OUT_REGEX

I call this script in this way:

 ./script "/foo1/\|/foo2\/foo3/" "/bar1/\|/bar2\/bar3/"

However, the loop never gets executed. I tried changing the " in the command line arguments to '. But that did not help. I tried changing the greps to sed commands like so:

find . -name '*'.cpp | sed "\m%$IN_REGEX%" | sed "\%$OUT_REGEX%d"

Again, no success. However, when I try to execute the grep on the bash shell directly. It works fine. I have spent the whole day today trying to figure this out.

Can someone please help me out?

2 Answers 2


You can use the !(negate) and -path command-switches of find to accomplish this

$ find . \( ! -path "*bar*" -a ! -path "*bar2\/bar3*" -a -path "*foo*" -print \)

This will search in folders excluding bar, bar2/bar3, and including folders with foo in path. Give this a try. The syntax might change with different versions of find command.

Refer find man page for more details.


It seams to work fine if you remove the " line 1 and 2 when you are receiving the arguments :


find . -name '*'.cpp | grep $IN_REGEX | grep -v $OUT_REGEX
  • 2
    Quotes won't make a difference there in any Bourne-like shell let alone bash. More likely there was some invisible character like a carriage return after the quote. You need quotes around $IN_REGEX and $OUT_REGEX though (and -- to mark the end of options or use the -e option to grep). You might want the -E option so you can replace your \| (which by the way is not standard) with | (which is standard). Mar 1, 2013 at 15:18

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.