2012-06-21 22 views
0

我已經解析了在TCL一個文件,我看這樣行:你怎麼能丟棄在解析文件線TCL

while {[gets $thefile line] >= 0} { ... 

和搜索我的模式一樣,

if { [regexp {pattern} $line] } { ... 

我想將第n + 2行存儲在一個變量中,我該如何做到這一點(我無法嘗試在下一行找到模式,因爲它總是在變化)?

非常感謝

回答

1

最簡單的方法是把一個額外的getsif體內:

while {[gets $thefile line] >= 0} { 
    # ... 
    if { [regexp {pattern} $line] } { 
     if {[gets $thefile secondline] < 0} break 
     # Now $line is the first line, and $secondline is the one after 
    } 
    # ... 
} 
+0

它工作正常謝謝 – heyhey

0

你可以建立你的格局空間,在運行時的列表。例如:

set lines {} 
set file [open /tmp/foo] 
while { [gets $file line] >=0 } { 
    if { [llength $lines] >= 3 } { 
     set lines [lrange $lines 1 2] 
    } 
    lappend lines $line 
    if { [llength $lines] >= 3 } { 
     puts [join $lines] 
    } 
} 

第三次通過循環之後,將始終保持最近的三個行。在我的樣本,輸出結果如下:

line 1 line 2 line 3 
line 2 line 3 line 4 
line 3 line 4 line 5 
line 4 line 5 line 6 
line 5 line 6 line 7 
line 6 line 7 line 8 
line 7 line 8 line 9 

然後,您可以搜索內循環使用正則表達式。

+0

這是一個功能強大的解決方案謝謝你 – heyhey