如何将File line reader推进到下一行?

时间:2014-01-09 17:05:48

标签: ruby

我在脚本中有一个场景我正在写我所做的事情:

完整要点:https://gist.github.com/calebtote/8337449

sourceFile.each_line do |line|
    if (line.start_with?(*criteria)) then 
        buffer << line
        buffer << "\n\n"
    end
end

但是,我想为此添加额外的标准并不是那么简单。例如,我希望能够解析异常,这可能不是单行事件..所以在伪,我想要类似的东西:

sourceFile.each_line do |line|
    if (line.start_with?(*criteria)) then 
        buffer << line
        buffer << "\n\n"
    elsif (line.start_with?("Exception:")) then
            buffer << line
            line.advance #<- not sure what do to here
            while !line.chomp.empty?
    end
end

编辑1:

澄清预期的投入/产出:

# input file
13:37:09:299         DBA               20      
SELECT Name from Table


Exception: Error code 50100
Description: Bad stuff!
Line number 243, File name: myfile.cpp
Time: 12/31/2013 08:24:20

13:37:09:301         Identity_FW       10      
In ApplicationIdentity::operator==

#output file
Exception: Error code 50100
Description: Bad stuff!
Line number 243, File name: myfile.cpp
Time: 12/31/2013 08:24:20

2 个答案:

答案 0 :(得分:1)

如果这就是你正在做的事情,就不需要逐行解析。

destFile.puts sourceFile.read.split("\n\n").select { |x| x =~ /^Exception: / }

答案 1 :(得分:0)

Ruby的Enumerable有一个名为slice_before的好方法,可以轻松完成这类任务。

从“test.log”开始,如下所示:

#begin log data above this

Exception: Error code 50100
Description: Bad stuff!
Line number 243, File name: myfile.cpp
Time: 12/31/2013 08:24:20

#continue log
#continue log
#continue log
#continue log

Exception: Error code 50100
Description: Bad stuff!
Line number 243, File name: myfile.cpp
Time: 12/31/2013 08:24:20

#continue log
#continue log
#continue log
#continue log

此代码会将其分解为可以轻松解析的块:

File.foreach('test.log').slice_before(/^\s*$/).to_a 
# => [["#begin log data above this\n"],
#     ["\n",
#      "Exception: Error code 50100\n",
#      "Description: Bad stuff!\n",
#      "Line number 243, File name: myfile.cpp\n",
#      "Time: 12/31/2013 08:24:20\n"],
#     ["\n",
#      "#continue log\n",
#      "#continue log\n",
#      "#continue log\n",
#      "#continue log\n"],
#     ["\n",
#      "Exception: Error code 50100\n",
#      "Description: Bad stuff!\n",
#      "Line number 243, File name: myfile.cpp\n",
#      "Time: 12/31/2013 08:24:20\n"],
#     ["\n",
#      "#continue log\n",
#      "#continue log\n",
#      "#continue log\n",
#      "#continue log\n"]]

您不需要to_a来循环它。做类似的事情:

File.foreach('test.log').slice_before(/^\s*$/).each do |chunk|
  # process the chunk
end 

您可以使用readlines代替foreach。最终结果应该是相同的。