Take the 2-minute tour ×

I have 10 folders having names 1 to 10. There are multiple files under each of these folders. I want to look for a pattern inside selective folders such as in files contained in folders named 2 to 6. How do I achieve this on the shell? I know there's a way to do it using the for loop in shell scripts as described below:

for ((i=2;i<=6;i++)); do grep 'pattern' $i/*; done

but in this case it is going to fire 5 different grep commands which I would need to collate in the end.

Is there a direct regex syntax to accomplish this?

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

If I understood your question correctly, you can do brace expansion like:

grep 'pattern' {2..6}/*
share|improve this answer
Or, as long as it's simple, character classes: grep foo [2-6]/* –  Kevin Oct 20 '13 at 21:17
@Berei,Kevin - Thanks! –  Abhishek Jain Oct 21 '13 at 3:06
add comment

You could use the -r option and the --exclude-dir option.

-r, --recursive
Read all files under each directory, recursively, following symbolic links only 
if they are on the command line.  This is equivalent to the -d recurse option.

Exclude directories matching the pattern DIR from recursive searches.


f1 f2  f3  f4  f5  f6  f7  f8  f9 f10

Each folder contains a file file with the string abc inside:

$ grep --exclude-dir 'f[1,7-9]' --exclude-dir 'f10' -r 'abc'       
share|improve this answer
add comment

Your Answer


