An Array of grep Results?


#1

I want to search all the files in a directory for a string and save the
results in an Array. So far, the best solution I can come up with is
using system(“grep … > resultsFile”), then opening resultsFile and
doing readlines(). There’s a better way, isn’t there?


#2

On Sat, 2006-03-11 at 07:32 +0900, Nathan O. wrote:

I want to search all the files in a directory for a string and save the
results in an Array. So far, the best solution I can come up with is
using system(“grep … > resultsFile”), then opening resultsFile and
doing readlines(). There’s a better way, isn’t there?

Yep: Dir["/some/foo/directory/*"] :wink:

See the docs for Dir#glob


#3

Nathan O. removed_email_address@domain.invalid wrote:

I want to search all the files in a directory for a string and save
the results in an Array. So far, the best solution I can come up with
is using system(“grep … > resultsFile”), then opening resultsFile
and doing readlines(). There’s a better way, isn’t there?

untested

found = {}
Dir["/foo/*"].each {|f| found[f] = File.open(f) {|io|
io.grep(/your_string/)} }

This should give you a hash with file names as keys and match lines as
values.

Kind regards

robert