Insuzu
Insuzu

Reputation: 19

How to access a value from a file in tcl script

I have a file 'example.txt' The content of example.txt are as follows,

NAME     Subject  Y/N   SCORE      SPEED
Ramesh | Science | - | 11090 (P) | Slow
Matt   | English | - | 11020 (F) | Fast
John   | Computer| Y | 12233 (P) | Fast

I want to read the SCORE of Ramesh (i.e. 11090) and store it in a variable to process it further. I need to write a TCL script for the same.

How do I access 11090 and store in a variable say, a?

Upvotes: 0

Views: 882

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

In your file, except for the first line, you're using newline as a record separator and | as a field separator. There's also padding in the fields. We can parse that like this:

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

We can also use the first line to generate names for the fields:

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

Upvotes: 2

Related Questions