开发者

How to extract specific values from a file in tcl

$$ comments             //not needed
$$ comments             /not needed   
$$
$$
$$ comments             //not needed
$$.INPUT a vcc            // needed 
$$.OUTPUT o                //needed 
$$.sdsds                        
$$
$$.sdsds 
$$ 
$$.s开发者_StackOverflow社区dsdsds

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

here are no spaces between lines $$


This is the sort of situation where a regular expression or a string format can help. However, it's not immediately clear what the format of the file is from the sample given; it's hard to tell exactly which bits are interesting, what the scope of variation in particular pieces is, etc. Still, we can take a few steps:

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"
        }
    }
}

Using it:

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

As noted, a regular expression could also work for parsing the data line, using regexp instead of scan to do the matching, but I don't understand the format well enough to be able to say what RE to use.


There are several libraries to process plain text files in the tcllib project and I'd recommend you look there.

If you insist on writing one yourself you can use something like this:

 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

EDIT: but please see Donal's answer as i find it better then my own.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜