Home > Blockchain >  Matching pattern and adding values to a list in TCL
Matching pattern and adding values to a list in TCL

Time:02-14

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

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.

CodePudding user response:

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
}
  • Related