简体   繁体   中英

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

eg, 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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM