如何从 tcl 脚本中的文件访问值

时间:2021-04-15 05:06:27

标签: shell scripting 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?

1 个答案:

答案 0 :(得分:2)

在您的文件中,除了第一行,您使用换行符作为记录分隔符,使用 | 作为字段分隔符。田间也有填充物。我们可以这样解析:

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
相关问题