Forum: Ruby An Array of grep Results?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Nathan O. (Guest)
on 2006-03-11 00:32
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?
Jonathan L. (Guest)
on 2006-03-11 00:51
(Received via mailing list)
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/*"] ;)

See the docs for Dir#glob
Robert K. (Guest)
on 2006-03-11 14:59
(Received via mailing list)
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
This topic is locked and can not be replied to.