Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

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 
]
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 ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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,}|
} $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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...