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.
7863582496e914f1ffce56f98d468f72?d=identicon&s=25 Nathan Olberding (nko)
on 2006-03-10 23: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?
9d4ec8946f933a18a1d15b094cc3c425?d=identicon&s=25 Jonathan Leighton (Guest)
on 2006-03-10 23:51
(Received via mailing list)
On Sat, 2006-03-11 at 07:32 +0900, Nathan Olberding 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
5befe95e6648daec3dd5728cd36602d0?d=identicon&s=25 Robert Klemme (Guest)
on 2006-03-11 13:59
(Received via mailing list)
Nathan Olberding <nathan.olberding@gmail.com> 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.