我需要在下面的列表中更改vlan 1到555:
file.txt的
SW1#sh interfaces status
Port Name Status Vlan Duplex Speed Type
Fa0/1 connected trunk full 100 10/100BaseTX
Fa0/2 notconnect 1 auto auto 10/100BaseTX
Fa0/3 notconnect 1 auto auto 10/100BaseTX
Fa0/4 notconnect 1 auto auto 10/100BaseTX
Fa0/5 connected 1 a-full a-100 10/100BaseTX
Fa0/6 notconnect 1 auto auto 10/100BaseTX
Fa0/7 connected 1 a-half a-10 10/100BaseTX
Fa0/8 connected 1 a-full a-100 10/100BaseTX
Fa0/9 notconnect 1 auto auto 10/100BaseTX
Fa0/10 notconnect 1 auto auto 10/100BaseTX
Fa0/11 connected 1 a-full a-100 10/100BaseTX
Fa0/12 notconnect 1 auto auto 10/100BaseTX
Fa0/13 notconnect 1 auto auto 10/100BaseTX
Fa0/14 notconnect 1 auto auto 10/100BaseTX
Fa0/15 notconnect 1 auto auto 10/100BaseTX
Fa0/16 notconnect 1 auto auto 10/100BaseTX
Fa0/17 notconnect 1 auto auto 10/100BaseTX
Fa0/18 notconnect 1 auto auto 10/100BaseTX
Fa0/19 notconnect 1 auto auto 10/100BaseTX
Fa0/20 notconnect 1 auto auto 10/100BaseTX
Fa0/21 notconnect 1 auto auto 10/100BaseTX
Fa0/22 notconnect 1 auto auto 10/100BaseTX
Fa0/23 notconnect 1 auto auto 10/100BaseTX
Fa0/24 TRUNK VOICE BRANCH connected 100 a-full a-100 10/100BaseTX
Gi0/1 connected trunk a-full a-1000 10/100/1000BaseTX
Gi0/2 notconnect 1 auto auto Not Present
代码:
set f [open "file.txt" r]
foreach a [split [read -nonewline $f] \n] {
set 0 [lindex $a 0]
set b [lsearch -inline -regexp $a "1"]
if { [regexp {^F|^G|^P} $0] && $b == "1"} {
puts "conf t"
puts "interface $0"
puts "switchport access vlan 555"
}
}
Output:
conf t
interface Fa0/2
switchport access vlan 555
conf t
interface Fa0/3
switchport access vlan 555
conf t
interface Fa0/4
switchport access vlan 555
conf t
interface Fa0/5
switchport access vlan 555
conf t
interface Fa0/6
switchport access vlan 555
conf t
interface Fa0/7
switchport access vlan 555
conf t
interface Fa0/8
switchport access vlan 555
conf t
interface Fa0/9
switchport access vlan 555
conf t
interface Fa0/20
switchport access vlan 555
conf t
interface Fa0/22
switchport access vlan 555
conf t
interface Fa0/23
switchport access vlan 555
conf t
interface Gi0/2
switchport access vlan 555
如何看,端口Fa0 / 10直到Fa0 / 19和端口Fa0 / 21没有配置。我尝试用其他东西改变lsearch,但直到现在我都失败了。
我期望的正确输出是所有带vlan 1的端口我需要更改为vlan 555.我怎么能这样做?
Tkanks。
答案 0 :(得分:1)
问题是lsearch -inline -regexp $a "1"
找到任何类型的字符串,其中包含" one"其中的数字,例如19.后来,当它与$b == "1"
中的1进行比较时,会变为19 == 1
,但会失败。
解决方案是通过使用几个可能的正则表达式之一将匹配限制为完全字符串1
:{\m1\M}
是一个,但{\y1\y}
或{^1$}
也适用
请注意,这段代码仍然有点脆弱(例如,第一行的匹配仅仅是巧合)。
if {[string match {[FGP]*} $a] && [string range $a 42 52] == 1}
可能会更好。
文档:if,lsearch,Syntax of Tcl regular expressions,string
(请参阅" Constraint escapes"在正则表达式语法文档中。)