2011-08-01 23 views
0

我是编程新手请帮助我。 我需要根据时间从特定行读取文件并将其写入另一个文件。但是在写入其他文件时跳过第一行。从包含ruby中的一些关键字的特定行读取文件

timeStr="2011-08-01 02:24" 
File.open(path+ "\\logs\\messages.log", "r") do |f| 
    # Skip the garbage before pattern: 
    while f.gets !~ (/#{timeStr}/) do; end     
    # Read your data: 
    while l = f.readlines 
    File.open(path+ "\\logs\\messages1.log","a") do |file1| 
     file1.puts(l) 
    end 
    end 
end 

当运行上述脚本时,跳过匹配timeStr的第一行并从第二行将文件写入到messages1中。当我打开messages1.log文件时,包含匹配字符串的第一行将不会出现。任何想法在写入messages1.log文件的同时如何包含第一行。

回答

0

我想你想保持匹配/#{timeStr}/行,但这个循环:

while f.gets !~ (/#{timeStr}/) do; end 

它扔了出去。你能重新事情有点:

# Get `line` in the right scope. 
line = nil 

# Eat up `f` until we find the line we're looking for 
# but keep track of `line` for use below. 
while(line = f.gets) 
    break if(line =~ /#{timeStr}/) 
end 

# If we found the line we're looking for then get to work... 
if(line) 
    # Grab the rest of the file 
    the_rest = f.readlines 
    # Prepend the matching line to the rest of the file 
    the_rest.unshift(line) 
    # And write it out. 
    File.open(path + "\\logs\\messages1.log","a") do |file1| 
     file1.puts(the_rest) 
    end 
end 

我没有测试过这一点,但它应该工作霸菱错别字等。

+0

嘿,谢谢,它的工作正常使用您提供的代码:) – wani

相关问题