parul71625
parul71625

Reputation: 193

How to parse a text file in tcl using separators?

I have a text file of the format

35|46

36|49

37|51

38|22

40|1

39|36

41|4

I have to read the file into an array across the separator "|" where left side will be the key of the array and right side will be the value.

I have used the following code

foreach {line} [split [read $lFile] \n] {
    #puts $line
    foreach {lStr} [split $line |] {
        if { $lStr!="" } {
            set lPartNumber [lindex $lStr 0]
            set lNodeNumber [lindex $lStr 1]
            set ::capPartsInterConnected::lMapPartNumberToNodeNumber($lPartNumber) $lNodeNumber

        }
    }

}

close $lFile

I am not able to read the left side of the separator "|". How to do it?

And similarly for this :

35|C:\AI\DESIGNS\SAMPLEDSN50\BENCH_WORKLIB.OLB|R

36|C:\AI\DESIGNS\SAMPLEDSN50\BENCH_WORKLIB.OLB|R

I need to assign all three strings in different variables

Upvotes: 1

Views: 1491

Answers (1)

Dinesh
Dinesh

Reputation: 16428

You are making mistake in the foreach where the result of split will be assigned to a loop variable lStr where it will contain only one value at a time causing the failure.

With lassign, this can be performed easily.

set fp [open input.txt r]
set data [split [read $fp] \n]
close $fp

foreach line $data {
    if {$line eq {}} {
        continue
    }
    lassign [split $line | ] key value
    set result($key) $value
}   
parray result

lassign [split "35|C:\\AI\\DESIGNS\\SAMPLEDSN50\\BENCH_WORKLIB.OLB|R" |] num userDir name
puts "num : $num"
puts "userDir : $userDir" 
puts "name : $name"

Upvotes: 4

Related Questions