set oldline "This is how the line reads before replacement"
set newline "This is how the line should read after replacement"
set id [open filename.txt r]
set data [split [read -nonewline $id] \n]
close $id
for {set loop 0} {$loop < [llength $data]} {incr loop} {
if {[string equal $oldline [lindex $data $loop]]} {
lreplace $data $loop $loop $newline
}
}
set id [open filename.txt w]
puts -nonewline $id [join $data \n]
close $id
There are obviously variations on this theme. You might only know part of the line and need to use 'string match' or 'string match -nocase' or even a 'regexp' to determine if it is the line to be replaced.
You may also only require the first incidence of a line to be changed, in which case you would have to break out of the 'for' loop after finding it.
bind pub - !line changeline
proc changeline { nick uhost hand chan text } {
set line "3"
set file "scripts/script.tcl"
set changelineto "$text"
[[ Code to change the line ]]
putserv "privmsg $chan :Changed"
}
# read data from file
set data [split [read [set id [open $file]]][close $id] \n]
# replace 4th line (index 3)
set data [lreplace $data 3 3 $changelineto]
# rewrite the file with changed data
puts [set id [open $file w]] [join $data \n]
close $id
Note that index 3 in Tcl means the 4th line (starting from 0).