2011-08-01 19 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に一致する最初の行はスキップされ、2行目からファイルは、メッセージ1に書き込まれます。 messages1.logファイルを開くと、一致する文字列を含む最初の行は存在しません。 messages1.logファイルへの書き込み中に最初の行をインクルードする方法。

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

はそれを捨て:

答えて

0

は、私はあなたが/#{timeStr}/と一致する行が、このループを維持したいと思います。

# 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

関連する問題