如何解决如何从 tcl 脚本中的文件访问值
我有一个文件“example.txt” example.txt的内容如下,
NAME Subject Y/N score SPEED
Ramesh | Science | - | 11090 (P) | Slow
Matt | English | - | 11020 (F) | Fast
John | Computer| Y | 12233 (P) | Fast
我想读取 Ramesh 的 score(即 11090)并将其存储在一个变量中以进一步处理它。我需要为此编写一个 TCL 脚本。
如何访问 11090 并将其存储在变量中,例如 a?
解决方法
在您的文件中,除了第一行,您使用换行符作为记录分隔符,使用 |
作为字段分隔符。田间也有填充物。我们可以这样解析:
set f [open "yourfile.txt"]
gets $f; # Discard the first line!
set data [read $f]
close $f
foreach line [split $data "\n"] {
set fields [lmap field [split $line "|"] {string trim $field}]
# Assume the first field is a primary key
set records([lindex $fields 0]) $field
}
puts [lindex $records(Ramesh) 3]
# Extract the leading numeric bit of that field of that record
scan [lindex $records(Ramesh) 3] %d score
puts $score
我们也可以使用第一行来为字段生成名称:
set f [open "yourfile.txt"]
# "Helpfully" the first line is in a different format to the others
set fieldNames [regexp -all -inline {\S+} [gets $f]]
set data [read $f]
close $f
foreach line [split $data "\n"] {
set fields [lmap field [split $line "|"] {string trim $field}]
# Assume the first field is a primary key
set pk [lindex $fields 0]
foreach fieldName $fieldNames fieldValue $fields {
dict set records($pk) $fieldName $fieldValue
}
}
puts [dict get $records(Ramesh) "SCORE"]
# Extract the leading numeric bit of that field of that record
scan [dict get $records(Ramesh) "SCORE"] %d score
puts $score
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。