我是TCL的新手。我只想通过在TCL中使用ip地址和使用regexp的Expect来提取接口名称

时间:2017-02-02 19:24:37

标签: tcl expect

我的输入数据是:

Interface                  IP-Address      OK? Method Status                Protocol
Embedded-Service-Engine0/0 unassigned      YES NVRAM  administratively down down    
GigabitEthernet0/0         unassigned      YES NVRAM  up                    up      
GigabitEthernet0/0.10      10.1.1.1        YES NVRAM  up                    up      
GigabitEthernet0/0.20      20.1.1.2        YES NVRAM  up                    up      
GigabitEthernet0/1         192.168.2.1   YES NVRAM  up                    up      
GigabitEthernet0/2         192.168.1.1   YES NVRAM  up                    up   

我想要一种在给定IP地址的情况下提取接口名称的方法。例如,如果输入为192.168.1.1,则输出应为GigabitEthernet0/2

有人能帮助我吗?我试过这个:

regexp -line -- ^.*?(?=(?:\\..*?)?\\s$ip) $input

1 个答案:

答案 0 :(得分:1)

到目前为止,解决这类事情的最简单方法是解析行以进行某种映射,可能在数组中,然后在其中进行查找。要解析数据,我们将使用regexp -all -line -inline;这是非常有用的组合,因为它会生成我们可以使用foreach处理的列表来制作我们的地图。

# You might read this data from another program or from a file; that's good too...
set data "Interface                  IP-Address      OK? Method Status                Protocol
Embedded-Service-Engine0/0 unassigned      YES NVRAM  administratively down down    
GigabitEthernet0/0         unassigned      YES NVRAM  up                    up      
GigabitEthernet0/0.10      10.1.1.1        YES NVRAM  up                    up      
GigabitEthernet0/0.20      20.1.1.2        YES NVRAM  up                    up      
GigabitEthernet0/1         192.168.2.1   YES NVRAM  up                    up      
GigabitEthernet0/2         192.168.1.1   YES NVRAM  up                    up   "

# Build the mapping; the “-” in the variable name list is for skipping some unwanted stuff
foreach {- interface ip} [regexp -all -line -inline {^(\w+/\d+)\s+([\d.]+)} $data] {
    set mapToIP($interface) $ip
    set mapToInterface($ip) $interface
}

然后我们可以随时轻松地进行查找:

set myIP 192.168.1.1
puts "$myIP is mapped to interface: $mapToInterface($myIP)"

FWIW,你真的需要确保你总是将RE放在大括号中,因为它避免了各种各样的问题。虽然你应该总是支持你的RE不是100%规则,但你应该这样做,直到你绝对无法避免在运行时从单个部分构建RE,这在实际代码中是非常罕见的。

相关问题