# Using popen & grep

**URL:** <https://www.ruby-forum.com/t/using-popen-grep/186708>\
**Category:** Ruby\
**Created:** [April 12, 2010, 1:40am UTC](https://www.ruby-forum.com/t/using-popen-grep/186708 "2010-04-12T01:40:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![dankitania](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e9a140/32.png) [@dankitania](https://www.ruby-forum.com/u/dankitania)\
**Post date:** [April 12, 2010, 1:40am UTC](https://www.ruby-forum.com/t/using-popen-grep/186708/1 "2010-04-12T01:40:34Z")

</div>

I’m relatively new to ruby and to practice I’ve put together the code  
below - it’s supposed take two arguments then apply it to a grep command  
and display the output. Currently, nothing is outputted to the console.  
Anyone see what I’m doing wrong, thanks.

1 #!/usr/bin/ruby  
2  
3 results = IO.popen(“grep -i #{ARGV[0]} #{ARGV[1]}”, “r”)  
4 while output = results.gets  
5 puts output  
6 end  
7 results.close

---

<div class="post-metadata">

**Author:** ![dankitania](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e9a140/32.png) [@dankitania](https://www.ruby-forum.com/u/dankitania)\
**Post date:** [April 12, 2010, 2:42am UTC](https://www.ruby-forum.com/t/using-popen-grep/186708/2 "2010-04-12T02:42:43Z")

</div>

Dan K. wrote:

> I’m relatively new to ruby and to practice I’ve put together the code  
> below - it’s supposed take two arguments then apply it to a grep command  
> and display the output. Currently, nothing is outputted to the console.  
> Anyone see what I’m doing wrong, thanks.
> 
> 1 #!/usr/bin/ruby  
> 2  
> 3 results = IO.popen(“grep -i #{ARGV[0]} #{ARGV[1]}”, “r”)  
> 4 while output = results.gets  
> 5 puts output  
> 6 end  
> 7 results.close

cmd=“grep -i #{ARGV[0]} #{ARGV[1]}”  
puts cmd

results = IO.popen(cmd, “r”)  
while output = results.gets  
puts output  
end  
results.close

you should chech ARGV is correct. you can run cmd on console to see  
result,cheers!

---

<div class="post-metadata">

**Author:** ![dankitania](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e9a140/32.png) [@dankitania](https://www.ruby-forum.com/u/dankitania)\
**Post date:** [April 13, 2010, 8:35am UTC](https://www.ruby-forum.com/t/using-popen-grep/186708/3 "2010-04-13T08:35:45Z")

</div>

On 04/12/2010 01:40 AM, Dan K. wrote:

> 6 end  
> 7 results.close

A few remarks: the block form of IO.popen is more robust because it  
ensures proper closing of file handles. Also, using an array as first  
argument avoids quoting issues - you need 1.9 for this. Thus you could  
do:

IO.popen [“grep”, “-i”, \*ARGV[0…1]], “r” do |io|  
io.each\_line do |line|  
puts line  
end  
end

However, much easier would be to read and grep yourself in Ruby:

rx = Regexp.new(ARGV[0], Regexp::IGNORECASE)

File.foreach ARGV[1] do |line|  
puts line if rx =~ line  
end

Kind regards

robert
