在当前行继续 while 循环

Continue a while loop on current line

我写了一个脚本,可以在思科设备上执行很多命令。如果sw或router出现问题导致程序停止,我需要删除当前行之前的所有行。

示例:

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...
}

你可以这样做:

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

根据格伦的回答,我这样做了:

#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".