我写了一个脚本,在cisco设备上执行了很多命令。如果sw或路由器出现问题且程序停止,我需要删除当前行之前的所有行。
示例:
ips.txt
169.254.0.1
169.254.0.2
169.254.0.3 <- For any reason, the program stop here (no login or the device becomes unreachable or anyway)
169.254.0.4
在
ips.txt
169.254.0.3 <- Run again after treat a problem on device
169.254.0.4
如何在循环的同一行继续循环而不手动删除行?
这是循环部分:
set f [open "ips.txt" r]
set lines [split [read $f] "\n"]
close $f
set n [llength $lines]
set i 0
while { $i <= $n } {
set nl [lindex $lines $i]
set l3 [split $nl ","]
set IP_SW [lindex $l3 0]
set IP_RT [lindex $l3 1]
do a lot of tcl and expect commands...
}
答案 0 :(得分:1)
set filename ips.txt
set num_processed 0
while {...} {
# ...
if {successfully processed this one} {
incr num_processed
}
}
# out of the while loop, remove the first N lines from the file
# assuming your system has GNU sed
exec sed -i.bak "1,${num_processed}d" $filename
# or with Tcl
set fin [open $filename]
set fout [open $filename.new w]
set n 0
while {[gets $fin line] != -1} {
if {[incr n] <= $num_processed} continue
puts $fout $line
}
file link -hard $filename.bak $filename
file rename -force $filename.new $filename
答案 1 :(得分:0)
根据格伦的回答,我这样做了:
#inside while loop
while { $i <= $n } {
set nl [lindex $lines $i]
set l3 [split $nl ","]
set IP_SW [lindex $l3 0]
set IP_RT [lindex $l3 1]
# condition to continue on current line, even the program exit unexpectedly
set laststop [open "roundline.txt" w]
puts $laststop "previousround"
puts $laststop "$IP_SW $IP_RT"
close $laststop
}
#out of while loop
set laststop [open "roundline.txt" r]
foreach a [split [read -nonewline $laststop] \n] {
set LINE [lindex $a 0]
if { $LINE != "previousround" } {
exec sed -i "/$LINE\/ipreviousround" ips.txt
exec sed -i "0,/previousround/d" ips.txt
}
}
现在,如果程序因任何原因停止,文件“roundline.txt”将保存最后一行。然后我插入“previousround”只是为了匹配我的行。之后,我删除了第一行,直到“previousround”。