Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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:

IN_REGEX="$1"
OUT_REGEX="$2"

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?

share|improve this question

2 Answers 2

up vote 0 down vote accepted

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

IN_REGEX=$1
OUT_REGEX=$2

find . -name '*'.cpp | grep $IN_REGEX | grep -v $OUT_REGEX
share|improve this answer
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). –  Stéphane Chazelas Mar 1 '13 at 15:18

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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