Ruby grep with line number

2020-08-20 15:10发布

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).

标签: ruby grep
9条回答
爷、活的狠高调
2楼-- · 2020-08-20 15:52

Another suggestion:

lines.find_index{ |l| l=~ regex }.

查看更多
神经病院院长
3楼-- · 2020-08-20 15:53

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
查看更多
Deceive 欺骗
4楼-- · 2020-08-20 15:57

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]]
查看更多
放荡不羁爱自由
5楼-- · 2020-08-20 15:59

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

查看更多
smile是对你的礼貌
6楼-- · 2020-08-20 16:00
>> lines=["one", "two", "tests"]
=> ["one", "two", "tests"]
>> lines.grep(/test/){|x| puts "#{lines.index(x)+1}, #{x}" }
3, tests
查看更多
做个烂人
7楼-- · 2020-08-20 16:00

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"} 
查看更多
登录 后发表回答