[英]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 我想提出
ACC_
后XYDATA
得到ACC_NAME1
,如果文件中包含一个以上的字符串XYDATA
,把VEL_
, DSP_
和Prs_
等
Using the textutil::split
package from tcllib , and the ability of foreach
to iterate over multiple lists simultaneously 使用tcllib的
textutil::split
包,以及让foreach
同时迭代多个列表的功能
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 或者,使用单个regsub调用生成一些代码
set code [regsub -all {(, )([^,]+)} $line {\1[lindex $prefixes [incr counter]]\2}]
set counter -1
puts [subst $code]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.