ManInTheMiddle
ManInTheMiddle

Reputation: 128

TCL, replacing strings in a textfile

lets say I open a file, then parsed it into lines. Then I use a loop:

foreach line $lines {}

e.g., if the file contained the following string:

XYDATA, NAME1 

I want to put ACC_ after the XYDATA to get ACC_NAME1 and if the file contains more than one strings with XYDATA, put VEL_, DSP_ and Prs_ and so on

Upvotes: 1

Views: 108

Answers (1)

glenn jackman
glenn jackman

Reputation: 247220

Using the textutil::split package from tcllib, and the ability of foreach to iterate over multiple lists simultaneously

package require textutil::split

set line {XYDATA, foo, bar, baz, qux}
set prefixes {ACC_ VEL_ DSP_ Prs_}

set fields [textutil::split::splitx $line {, }]
set new [list]

if {[lindex $fields 0] eq "XYDATA"} {
    lappend new [lindex $fields 0]
    foreach prefix $prefixes field [lrange $fields 1 end] {
        lappend new $prefix$field
    }
}
puts [join $new ", "]
XYDATA, ACC_foo, VEL_bar, DSP_baz, Prs_qux

alternately, use a single regsub call that generates some code

set code [regsub -all {(, )([^,]+)} $line {\1[lindex $prefixes [incr counter]]\2}]
set counter -1
puts [subst $code]

Upvotes: 1

Related Questions