TCL:匹配特定字符串后打印剩余的字符/字符串

时间:2021-01-08 13:13:41

标签: tcl

我有一个变量,

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"

如果我将输入作为“描述”,我需要将值打印为“10/100/Gig-Ethernet-TX-test”

同样,如果我的输入是“配置速度”,我需要将值打印为“1 Gbps”

我尝试过这样但没有正确获得“配置速度”的输出

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

对于“描述”,我得到的输出为 10/100/Gig-Ethernet-TX-test

对于“配置速度”,我得到的输出为“以太网”而不是“1 Gbps”

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

这是一种处理起来相当混乱的格式,因为它完全针对人而不是计算机进行了优化。我们可以整理它,但只是有点棘手:我们需要使用换行符和多空格序列作为基本分隔符。

# 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