Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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 have a nested folder structure containing lots of folders and files.

How do I search inside files for a pattern eg "sampletext", but only if the filename matches a pattern (eg only search inside files with .txt extension) and finally the containing folder name must match another pattern? (eg "data").

I'm sure I could write a shell script to do it, but I'm sure clever one-liners exist that will teach me new things!

Thanks in advance

share|improve this question
up vote 2 down vote accepted

Since you say you have a nested folder structure, I believe *data*/*txt won’t do what you need.  I suggest

find . –type d –name "*data*" –exec sh –c "grep sampletext /dev/null {}/*.txt" \;

The /dev/null is there to force grep to display the filename even when it runs on a directory that has only one .txt file in it.

share|improve this answer
Wicked, thanks. – jon Jan 3 '13 at 19:01

Your Answer


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.