Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am working with a certain framework which has modules with consistent folder naming conventions. I would like to retrieve all files containing partial string foo from a high level directory, but I only want results from files with a path containing a directory named Bar. To elaborate: from the root directory of the project, there are generally four levels of subfolders, containing an arbitrary number of subfolders and text files all .php). The subdirectories in which I would like to search / from which I would like results all contain a parent folder named Bar.

Stated relative to my limited experience: I would like a command such as grep -isrl 'foo' ./ and only receive results such as

./A/B/C/Bar/D/F/Some.php
./G/H/I/Bar/Some.php

and excluding

./A/B/C/Baz/D/F/Some.php
./G/H/I/Baz/Some.php

Essentially, I assume there's something like grep -isrl 'foo' ./*/Bar/*.php where * will match zero-to-many subdirectories.

share|improve this question
up vote 1 down vote accepted

One way:

find <search path> -type d -name 'Bar' -exec grep -r foo {} +

(without GNU find, replace + with \;).

This way will first find the directories that are named Bar and then recursively grep only in these.

To limit the search to PHP files:

find <search path> -type d -name 'Bar' -exec grep -r --include '*.php' foo {} +

It could also be done with shell globbing, but that depends on which shell you are using (obviously).

EDIT: Adding a Bash example:

shopt -s globstar
grep -r test <search path>/**/Bar/
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .