Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby grep with line number

Tags:

grep

ruby

What could be the best way of getting the matching lines with the line numbers using Ruby's Enumerable#grep method. (as we use -n or --line-number switch with grep command).

like image 894
intellidiot Avatar asked Apr 23 '11 00:04

intellidiot


4 Answers

A modification to the solution given by the Tin Man. This snippet will return a hash having line numbers as keys, and matching lines as values. This one also works in ruby 1.8.7.

text = 'now is the time
for all good men
to come to the aid
of their country'

regex = /aid/


hits = text.lines.each_with_index.inject({}) { |m, i| m.merge!({(i[1]+1) => i[0].chomp}) if (i[0][regex]); m}

hits #=> {3=>"to come to the aid"} 
like image 98
intellidiot Avatar answered Oct 19 '22 10:10

intellidiot


maybe something like this:

module Enumerable
  def lgrep(pattern)
    map.with_index.select{|e,| e =~ pattern}
  end
end
like image 24
J-_-L Avatar answered Oct 19 '22 09:10

J-_-L


Enumerable#grep doesn't let you do that, at least by default. Instead, I came up with:

text = 'now is the time
for all good men
to come to the aid
of their country'

regex = /aid/

hits = text.lines.with_index(1).inject([]) { |m,i| m << i if (i[0][regex]); m }
hits # => [["to come to the aid\n", 3]]
like image 31
the Tin Man Avatar answered Oct 19 '22 08:10

the Tin Man


This isn't elegant or efficient, but why not just number the lines before grepping?

like image 44
a3nm Avatar answered Oct 19 '22 08:10

a3nm