Giridharan L
Giridharan L

Reputation: 33

TCL : to print the remaining characters/string once the particular string is matched

I have a variable as in,

set recA "Description        : 10/100/Gig-Ethernet-TX-test
Interface          : 1/1/18                     Oper Speed       : N/A
Link-level         : Ethernet                   Config Speed     : 1 Gbps
Admin State        : down                       Oper Duplex      : N/A
Oper State         : down                       Config Duplex    : full"

If i give my input as "Description" , i need print the value as "10/100/Gig-Ethernet-TX-test"

Similarly, if my input is "Config Speed" , i need to print the values as "1 Gbps"

i tried like this but did not get the output properly for "Config Speed"

set lines [split $recA \n]
set index [lsearch -regexp $lines "Description"]
set match [lrange $lines [expr $index] [expr $index]]
set b [lindex [lindex [split [join $match " "] ":"] 1] 0]
puts $b

for "Description" i get the output as 10/100/Gig-Ethernet-TX-test

for "Config Speed" , i get the output as "Ethernet" instead of "1 Gbps"

Can someone help ?

Upvotes: 0

Views: 167

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

That's quite a messy format to handle as it is entirely optimised for people and not for computers. We can tidy it up, but only by being a bit tricky: we need to use newlines and multi-space sequences as basic separators.

# How to split by regular expression
set fields [split [regsub -all {[ ]{2,}|\n} $recA "\u0100"] "\u0100"]

# Clean the values up
set mapping [lmap f $fields {string trim $f " :"}]

# OK, now we have a dictionary and can just look things up in it
puts [dict get $mapping "Description"];   # >>> 10/100/Gig-Ethernet-TX-test
puts [dict get $mapping "Config Speed"];  # >>> 1 Gbps

Upvotes: 2

Related Questions