# An Array of grep Results?

**URL:** <https://www.ruby-forum.com/t/an-array-of-grep-results/79712>\
**Category:** Ruby\
**Created:** [March 10, 2006, 11:32pm UTC](https://www.ruby-forum.com/t/an-array-of-grep-results/79712 "2006-03-10T23:32:11Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![nko](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/91b2a8/32.png) [@nko](https://www.ruby-forum.com/u/nko)\
**Post date:** [March 10, 2006, 11:32pm UTC](https://www.ruby-forum.com/t/an-array-of-grep-results/79712/1 "2006-03-10T23:32:11Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![nko](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/91b2a8/32.png) [@nko](https://www.ruby-forum.com/u/nko)\
**Post date:** [March 10, 2006, 11:51pm UTC](https://www.ruby-forum.com/t/an-array-of-grep-results/79712/2 "2006-03-10T23:51:55Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![nko](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/91b2a8/32.png) [@nko](https://www.ruby-forum.com/u/nko)\
**Post date:** [March 11, 2006, 1:59pm UTC](https://www.ruby-forum.com/t/an-array-of-grep-results/79712/3 "2006-03-11T13:59:06Z")

</div>

Nathan O. [removed\_email\_address@domain.invalid](mailto: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

```
