问题
I was trying to redirect the output to a text file. It works as expected. However i would like to replace a word in the text file with a different string. I tried but it didn't work. Could you please help me with 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"
puts $output $expect_out(buffer)
expect "debugshell"
}
sleep 20
}
# i used regsub to replace the the string debugshell with shell
regsub -all debugshell $output shell output4
close $output
回答1:
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.
回答2:
You need to enclose your pattern in brackets:
regsub -all {debugshell} $output shell output4
This is pretty evident from the corresponding documentation:
http://www.tcl.tk/man/tcl8.6/TclCmd/regsub.htm
来源:https://stackoverflow.com/questions/23394788/how-to-replace-a-string-in-a-file-using-tcl-expect