Abhishek Jain
Abhishek Jain

Reputation: 4518

Querying selective files using grep

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?

Upvotes: 1

Views: 200

Answers (2)

Chris Seymour
Chris Seymour

Reputation: 85883

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-dir=DIR
Exclude directories matching the pattern DIR from recursive searches.

Demo:

ls
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'       
f5/file:abc
f4/file:abc
f2/file:abc
f3/file:abc
f6/file:abc

Upvotes: 2

Birei
Birei

Reputation: 36282

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

grep 'pattern' {2..6}/*

Upvotes: 2

Related Questions