Reputation: 11228
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).
Upvotes: 10
Views: 4866
Reputation: 1
Put text in a file
now is the time
for all good men
to come to the aid
of their country
Command line (alternative of grep or awk command )
ruby -ne ' puts $_ if $_=~/to the/' test.log
Try this also
ruby -na -e ' puts $F[2] if $_=~/the/' test.log
Similarly
ruby -na -e ' puts $_.split[2] if $_=~/the/' test.log
This is similar to awk command.
Upvotes: 0
Reputation: 11228
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"}
Upvotes: 1
Reputation: 6270
To mash up the Tin Man's and ghostdog74's answers
text = 'now is the time
for all good men
to come to the aid
of their country'
regex = /aid/
text.lines.grep(/aid/){|x| puts "#{text.lines.find_index(x)+1}, #{x}" }
# => 3, to come to the aid
Upvotes: 1
Reputation: 342977
>> lines=["one", "two", "tests"]
=> ["one", "two", "tests"]
>> lines.grep(/test/){|x| puts "#{lines.index(x)+1}, #{x}" }
3, tests
Upvotes: 1
Reputation: 160611
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]]
Upvotes: 9
Reputation: 156632
You can kludge it in Ruby 1.8.6 like so:
require 'enumerator'
class Array
def grep_with_index(regex)
self.enum_for(:each_with_index).select {|x,i| x =~ regex}
end
end
arr = ['Foo', 'Bar', 'Gah']
arr.grep_with_index(/o/) # => [[0, 'Foo']]
arr.grep_with_index(/a/) # => [[1, 'Bar'], [2, 'Gah']]
Or if you're looking for tips on writing a grep-like utility in Ruby. Something like this should work:
def greplines(filename, regex)
lineno = 0
File.open(filename) do |file|
file.each_line do |line|
puts "#{lineno += 1}: #{line}" if line =~ regex
end
end
end
Upvotes: 1
Reputation: 9177
maybe something like this:
module Enumerable
def lgrep(pattern)
map.with_index.select{|e,| e =~ pattern}
end
end
Upvotes: 7
Reputation: 8884
This isn't elegant or efficient, but why not just number the lines before grepping?
Upvotes: 4