An Array of grep Results?

N

Nathan Olberding

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?
 
J

Jonathan Leighton

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
 
R

Robert Klemme

Nathan Olberding said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top