In order to change a string in a file that you are writing, you need to change it in memory before you write it out. (Or you could write it out, read it in again, make the change, and write the changed version out. Which is totally making a meal out of it all!) Given that this is text output from a program that was originally intended for a person to read, it won't be that much. A few megabytes at most. That means that we can easily accumulate it in memory and do the write at the end.
set accumulate ""
for {set time 0} {$time < 3} {incr time} {
for {set times 0} {$times < 3} {incr times} {
log_user 0
exp_send "vmstat -n 2 5\r"
append accumulate $expect_out(buffer) "\n"
expect "debugshell"
}
sleep 20
}
regsub -all debugshell $accumulate shell accumulate_mapped
set output [open /scripts/cisco/output4 a+]
puts $output $accumulate_mapped
close $output
OK, since we're talking about applying the transformation to each line (that -all gives the game away) we can do the transformation as we go. In that case, we might do this:
set output [open /scripts/cisco/output4 a+]
for {set time 0} {$time < 3} {incr time} {
for {set times 0} {$times < 3} {incr times} {
log_user 0
exp_send "vmstat -n 2 5\r"
regsub -all debugshell $expect_out(buffer) shell mapped
puts $output $mapped
expect "debugshell"
}
sleep 20
}
close $output
Because the Expect capture buffer also traps newlines, you might consider using puts -nonewline instead of puts. It's also quite possible that this code won't do exactly what you expect; generally speaking, you're only really supposed to look at $expect_out(buffer) straight after an expect matches something.