2017-06-19 77 views
-1

如何逐個處理以File Id開頭的行之間的數據。我的下面的代碼給出第1節的輸出,如果有100 +節由File Id:分隔。閱讀文件內容並在Ruby中處理數據

它就像我想拿第一節編排數據然後拿第二節(File ID)等。如果有更好的辦法,我一定會聽。謝謝。

輸入文件(input.txt

File Id: C:/my_files/00_Roll_Tom-values.txt 

#RakeBoss-Random as on 12/19/2016 
[groups] 
met = chk\rel_io_chk, chk\dev_op_io, 
div = chk\kzhr2x, chk\zz52t0, chk\czzjrt 
rakeonly = chk\rzgnsd, chk\cztw5h 

[/] 
@met = rw 
@div = rw 
@rakeonly = r 

File Id: C:/my_files/Rander-values.txt 

#RakeBoss-Jan 21st QA 
[groups] 
met = chk\rel_io_chk, chk\dev_op_io 
div = chk\541kmj, chk\zz52t0 
app_only = chk\zz9ycd 
check_io = chk\wder4, chk\zz9ycd 
div_write = chk\lo98j3 
year_on = chk\3w345f 
[/] 
@met = rw 
@div = rw 
@app_only= r 
@check_io = r 
@div_write = rw 
@year_on = r 

[/wedmin] 
@check_io = rw 
div_write= rw 

[/doc/prod] 
@div = rw 
@app_only = r 
year_on = rw 

File Id: C:/my_files/456_Milo_123-values.txt 

#RakeBoss-Jan 21st Prod 
[groups] 
met = chk\rel_io_chk, chk\dev_op_io 
div = chk\kzhr2x, chk\zz52t0, chk\czzjrt, chk\pzjwr3 
jee_only = chk\zz9ycd, chk\hz659l, chk\zzktgj, 
check_io = chk\8u7y01, chk\zz9ycd 
unique_key = chk\zz9ycd 
year_on = chk\dytg6 
[/] 
@met = rw 
@div = rw 
@rakeonly = r 

[/Release] 
@check_io = rw 
@unique_key = rw 

[/Redmine/Treehub] 
@div = r 
@jee_only = rw 

............. 
................... 
............. so on separated by File Id: 

代碼

File.open("input.txt", "r") do |f| 
    fight_info = f.read 
    m = fight_info.match(/File\sId(.+?)File\sId/m) 
    puts m 
end 
+0

輸入文件有多大?如果確保它始終適合內存,則可以使用'read'來「啜食」它,但通常不應該以這種方式處理生產系統中的文件。 –

回答

1

你可以做的方法對文件和分裂它的抽象的閱讀分爲幾個部分:

def split_by_file_id(file) 
    lines = [] 
    id = nil 
    File.foreach(file).with_index do |line, line_num| 
    if line =~ /^File Id: (.*)/m 
     yield id, lines if id 
     lines = [] 
     id = $1 
    else 
     lines << line if id 
    end  
    end 
    yield id, lines if id 
end 

# Code to process each section... 
split_by_file_id("input.txt") do |id, lines| 
    lines.each do |line| 
    # do something... 
    end 
end 
+0

非常感謝,如何在[組]和[/]中組織數據 例如,從第1節開始,應該將scm,dev,readonly分配給名爲id的數組,並將其相應值逐個分配 – dev

0
file = File.open("input.txt", "rb") 
contents = file.read.split("File Id:") 
contents.shift 

現在,您可以使用contents.each來遍歷它。

+0

Be _very_小心這樣做。使用'read'會將整個文件拖入內存中,這會破壞性能。請參閱https://stackoverflow.com/q/25189262/128421 –