user788171
user788171

Reputation: 17553

grep for string in all files in directories with certain names

I have csv files in directories with this structure:

20090120/
20090121/
20090122/
etc...

I want to grep for a certain string in all of the csv files in these directories, but only for January 2009, e.g. 200901*/*.csv

Is there a bash command line argument that can do this?

Upvotes: 7

Views: 19240

Answers (4)

tor
tor

Reputation: 11

Try a combination of find to search for specific filename patterns and grep for finding the pattern:

find . -name "*.csv" -print -exec grep -n "NEEDLE" {} \; | grep -B1 "NEEDLE"

Upvotes: 1

Debaditya
Debaditya

Reputation: 2497

Try this :

grep -lr "Pattern" 200901*/*.csv 

Upvotes: 4

paxdiablo
paxdiablo

Reputation: 881123

You need something like:

grep NEEDLE 200901*/*.csv

(assuming your search string is NEEDLE of course - just change it to whatever you're actually looking for).

The bash shell is quite capable of expanding multi-level paths and file names.

That is, of course, only limited to the CSV files one directory down. If you want to search entire subtrees, you'll have to use the slightly mode complicated (and adaptable) find command.

Though, assuming you can set a limit on the depth, you could get away with something like (for three levels):

grep NEEDLE 200901*/*.csv 200901*/*/*.csv 200901*/*/*/*.csv 

Upvotes: 5

Phil Frost
Phil Frost

Reputation: 3956

Yes. grep "a certain string" 200901*/*.csv.

Upvotes: 13

Related Questions