2011-08-01 54 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

相關問題