带行号的Ruby grep
使用Ruby的带行号的Ruby grep,ruby,grep,Ruby,Grep,使用Ruby的Enumerable#grep方法,用行号获取匹配行的最佳方法是什么。(当我们使用-n或-line number和grep命令切换时)。这既不优雅也不高效,但为什么不在grep之前对行进行编号呢?您可以在Ruby 1.8.6中这样做: require 'enumerator' class Array def grep_with_index(regex) self.enum_for(:each_with_index).select {|x,i| x =~ regex}
Enumerable#grep
方法,用行号获取匹配行的最佳方法是什么。(当我们使用-n
或-line number
和grep命令切换时)。这既不优雅也不高效,但为什么不在grep之前对行进行编号呢?您可以在Ruby 1.8.6中这样做:
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']]
或者,如果您正在寻找用Ruby编写类似grep的实用程序的技巧。像这样的方法应该会奏效:
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
也许是这样的:
module Enumerable
def lgrep(pattern)
map.with_index.select{|e,| e =~ pattern}
end
end
Enumerable#grep不允许您这样做,至少在默认情况下是这样。相反,我想到了:
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]]
text=”现在是时候了
为了所有的好人
援助
他们国家的
regex=/aid/
hits=text.lines.with_index(1).injection([]){m,i | m[[“来帮助”\n“,3]]
把铁皮人和鬼怪的答案混在一起
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
对锡人给出的解决方案的修改。此代码段将返回一个哈希,其中行号作为键,匹配行作为值。此代码段也适用于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"}
将文本放入文件中
test.log
命令行(grep或awk命令的替代) 也试试这个
ruby -na -e ' puts $F[2] if $_=~/the/' test.log
同样地
ruby -na -e ' puts $_.split[2] if $_=~/the/' test.log
这类似于awk命令。另一个建议:
lines.find_index{l | l=~regex}
我只是对您使用的|e,|
符号感到好奇。这到底意味着什么?它丢弃了第二个参数(不需要)。如果我省略了它,e将变成两个参数的数组。+1这是一个非常好的常识性答案。不要再这样做。:-)我很想知道你的使用案例。我很好奇为什么`grep-n target file\u to\u search`
不够好。它速度非常快,支持grep的所有功能。@Tin-Man:Y是的,但我希望有一个平台独立性的ruby解决方案。@Phrogz:我的用例是从erb文件中选择一个特定的模式。+1因为我发现这个答案与我想要的最接近。我不得不对它进行一些更改,使其与1.8.7兼容。后来我发现,对于我的要求,如果结果是h,那将是非常好的ash,将行号作为键,行号作为值。我把它作为一个记录的答案。如果你在写问题之前知道你想要什么,并提出要求,这会对我们有很大帮助。你的最终结果将是微不足道的添加,然后将是你想要的。实际上,我的答案会更好。可以吗我不太同意铁皮人的观点。但你知道,有时候你在朝解决方案走了很多步之后,会改进你的想法:)这比其他任何解决方案都要优雅。希望我能投票。堆栈溢出需要更具动态性,并能适应不断变化的时间/范式。
ruby -ne ' puts $_ if $_=~/to the/' test.log
ruby -na -e ' puts $F[2] if $_=~/the/' test.log
ruby -na -e ' puts $_.split[2] if $_=~/the/' test.log