2011-08-01 4 views
0

프로그래밍에 익숙하지 않습니다. 시간을 기준으로 특정 라인의 파일을 읽고 다른 파일에 써야합니다. 그러나 다른 파일에 쓰는 동안 첫 줄을 건너 뜁니다.루비의 일부 키워드가 들어있는 특정 행의 파일 읽기

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 파일에 쓰는 동안 첫 번째 줄을 포함시키는 방법.

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

관련 문제