-->

Ruby grep with line number

2020-08-20 15:55发布

问题:

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

回答1:

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]]


回答2:

maybe something like this:

module Enumerable
  def lgrep(pattern)
    map.with_index.select{|e,| e =~ pattern}
  end
end


回答3:

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



回答4:

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


回答5:

>> lines=["one", "two", "tests"]
=> ["one", "two", "tests"]
>> lines.grep(/test/){|x| puts "#{lines.index(x)+1}, #{x}" }
3, tests


回答6:

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


回答7:

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"} 


回答8:

Put text in a file

test.log

 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.



回答9:

Another suggestion:

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



标签: ruby grep