| View previous topic :: View next topic |
| Author |
Message |
HÒóme Voice
Joined: 11 Sep 2009 Posts: 5
|
Posted: Fri Sep 18, 2009 1:37 pm Post subject: change a line in a file |
|
|
Hi.
How can i change a line in a file using eggdrop?
Thanks in advance |
|
| Back to top |
|
 |
TCL_no_TK Owner

Joined: 25 Aug 2006 Posts: 509 Location: England, Yorkshire
|
|
| Back to top |
|
 |
arfer Master

Joined: 26 Nov 2004 Posts: 436 Location: Manchester, UK
|
Posted: Fri Sep 18, 2009 3:01 pm Post subject: |
|
|
| Code: |
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. _________________ I must have had nothing to do |
|
| Back to top |
|
 |
HÒóme Voice
Joined: 11 Sep 2009 Posts: 5
|
Posted: Sat Sep 19, 2009 2:09 am Post subject: |
|
|
I cant run it.... Or has any error in code, or i am doing some thing wrong...
Well... i wanted something like this:
| Code: | 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"
} |
|
|
| Back to top |
|
 |
Sir_Fz Revered One

Joined: 27 Apr 2003 Posts: 3793 Location: Lebanon
|
Posted: Sat Sep 19, 2009 5:52 am Post subject: |
|
|
Since you have a specific line you wish to replace (3), then as demonstrated by arfer you can use [lreplace] to replace it.
| Code: | # 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). _________________ Follow me on GitHub
- Opposing
Public Tcl scripts |
|
| Back to top |
|
 |
HÒóme Voice
Joined: 11 Sep 2009 Posts: 5
|
Posted: Sat Sep 19, 2009 6:54 am Post subject: |
|
|
It works fine.
Thank you very much |
|
| Back to top |
|
 |
|