Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matching pattern and adding values to a list in TCL

I wondered if I could get some advice, I’m trying to create a list by reading a file with input shown below

Example from input file

Parameter.Coil = 1
Parameter.Coil.Info = Coil
BaseUTC.TimeSet_v0 = 1
BaseUTC.TimeSet_v0.Info = TimeSet_v0
BaseUTC.TimeSet_v1 = 1
BaseUTC.TimeSet_v1.Info = TimeSet_v1
BaseUTC.TimeSet_v14 = 1
BaseUTC.TimeSet_v14.Info = TimeSet_v14
BaseUTC.TimeSet_v32 = 1
BaseUTC.TimeSet_v32.Info = TimeSet_v32
VC.MILES = 1
VC.MILES.Info = MILES_version1

I am interested in any line with prefix of "BaseUTC." and ".Info" and would like to save value after "=" in a list

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Desired output = TimeSet_v0 TimeSet_v1 TimeSet_v14 TimeSet_v32

I’ve tried the following but not getting the desired output.

set input [open "[pwd]/Data/Input" r]

set list ""
while { [gets $input line] >= 0 } {
incr number
set sline [split $line "\n"]
if {[regexp -- {BaseUTC.} $sline]} {
#puts "lines = $sline"
if {[regexp -- {.Info} $sline]} {
set output [lindex [split $sline "="] 1]
lappend list $output
}}}
puts "output = $list"
close $input

I get output as

output = \ TimeSet_v0} \ TimeSet_v1} \ TimeSet_v14} \ TimeSet_v32}

Can any help identify my mistake, please.

Thank you in advance.

>Solution :

A lot of your code doesn’t seem to match your description (Steering? I thought you were looking for BaseUTC lines?), or just makes no sense (Why split what you already know is a single line on newline characters?), but one thing that will really help simplify things is a regular expression capture group. Something like:

#!/usr/bin/env tclsh

proc process {filename} {
    set in [open $filename]
    set list {}
    while {[gets $in line] >= 0} {
        if {[regexp {^BaseUTC\..*\.Info\s+=\s+(.*)} $line -> arg]} {
            lappend list $arg
        }
    }
    close $in
    return $list
}

puts [process Data/Input]

Or using wildcards instead of regular expressions:

proc process {filename} {
    set in [open $filename]
    set list {}
    while {[gets $in line] >= 0} {
        lassign [split $line =] var arg
        if {[string match {BaseUTC.*.Info} [string trim $var]]} {
            lappend list [string trim $arg]
        }
    }
    close $in
    return $list
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading