This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

change a line in a file

Help for those learning Tcl or writing their own scripts.
Post Reply
H
HÒóme
Voice
Posts: 5
Joined: Fri Sep 11, 2009 1:31 pm

change a line in a file

Post by HÒóme »

Hi.

How can i change a line in a file using eggdrop?

Thanks in advance
User avatar
TCL_no_TK
Owner
Posts: 509
Joined: Fri Aug 25, 2006 7:05 pm
Location: England, Yorkshire

Post by TCL_no_TK »

There is loads ov posts about this on the forum, try search'ing for them, best bet would be this post thou http://forum.egghelp.org/viewtopic.php?t=6885 :idea:
User avatar
arfer
Master
Posts: 436
Joined: Fri Nov 26, 2004 8:45 pm
Location: Manchester, UK

Post by arfer »

Code: Select all

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
H
HÒóme
Voice
Posts: 5
Joined: Fri Sep 11, 2009 1:31 pm

Post by HÒóme »

I cant run it.... Or has any error in code, or i am doing some thing wrong...

Well... i wanted something like this:

Code: Select all

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"
}
User avatar
Sir_Fz
Revered One
Posts: 3794
Joined: Sun Apr 27, 2003 3:10 pm
Location: Lebanon
Contact:

Post by Sir_Fz »

Since you have a specific line you wish to replace (3), then as demonstrated by arfer you can use [lreplace] to replace it.

Code: Select all

# 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).
H
HÒóme
Voice
Posts: 5
Joined: Fri Sep 11, 2009 1:31 pm

Post by HÒóme »

It works fine.


Thank you very much
Post Reply