2011-03-09 35 views
2
$$ comments    //not needed 
$$ comments    /not needed 
$$ 
$$ 
$$ comments    //not needed 
$$.INPUT a vcc   // needed 
$$.OUTPUT o    //needed 
$$.sdsds       
$$ 
$$.sdsds 
$$ 
$$.sdsdsds 

Mg1.qna o a vss vss n 0.36 0.03 mult=4 $$nnn //needed 
Mg1.qpa o a vcc vcc p 0.36 0.03 mult=6 $$nnn //needed 

這裏沒有空間之間的線路$$如何從文件中提取特定的值在TCL

回答

4

這是哪門子的情況下正則表達式或字符串格式可以提供幫助。但是,從給出的樣本中不清楚文件的格式是什麼;很難說究竟哪些位有趣的,有什麼變化的特殊部件的範圍,等等。不過,我們可以採取以下幾個步驟:

proc parseFileContents {contents infoVar} { 
    upvar 1 $infoVar inf 
    set lineNum 0 
    foreach line [split $contents "\n"] { 
     incr lineNum 
     # Skip comment lines (?) 
     if {[string match {$*} $line} continue 
     # Skip blank lines 
     if {[string trim $line] eq ""} continue 
     # Parse a "real" line 
     if {[scan $line "%s%s%s%s%s%s%f%f%s%s" a b c name d e value f g h] == 10} { 
      set inf($name) $value 
     } else { 
      # Oh dear, didn't work! 
      puts "warning: did not understand line $lineNum\n$line" 
     } 
    } 
} 

使用它:

parseFileContents $theContentsOfTheFile data 
puts "Keys: [array names data]" 
puts "VSS: $data(vss)" 
puts "VCC: $data(vcc)" 

如前所述,正則表達式也可以用於解析數據行,使用regexp而不是scan來進行匹配,但是我不明白該格式足以說明要使用哪個RE。

+0

@DKF - 我在此保證永遠不會發布關於Tcl的另一個答案:-)你總是打我,並寫出更好的答案。我們都非常感謝您的時間和知識 - 非常感謝! – 2011-03-09 09:59:37

+0

@尼爾:練習練習練習:-) – 2011-03-09 10:17:12

+0

+1和尊重這兩個,這個問題看起來像對我來說是胡言亂語,更不用說解決它了。 – Sii 2011-03-10 09:41:52

4

有幾個庫來處理tcllib項目中的純文本文件,我建議你看看那裏。

如果你堅持自己寫一個,你可以使用這樣的事情:

set fd [open $filename r] 
while { [gets $fd line] >= 0 } { 
     set data [split $line] 
     if { [lindex $data 0] == {$} } { 
        continue; #this is a comment line 
     } 
     puts [lindex $line 3]; #or whatever index you need... 
} 
close $fp 

編輯:但請參閱多納爾的答案,因爲我覺得它更好,然後我自己。

相關問題