How do i read a specific line from txt and or change it like i read line 5 and or i want to write to line 5 .. the reading i can do with counter and while but writing how would i do that ?
# Fetch a single line
proc getLine {file line} {lindex [split [read [set f [open $file]]][close $f] \n] $line}
# Insert data at the given line
# Accepts the same values for line number as 'linsert' does for index (check your manual)
# Will create the file if it doesn't exist.
proc addLine {file line data} {
if {[file readable $file]} {
set d [split [read [set f [open $file r+]]] \n]
seek $f 0
} {
set d ""
set f [open $file w]
}
puts -nonewline $f [join [linsert $d $line $data] \n]
close $f
}
# Replace one or more lines
# Usage: replaceLines <file> <first line> <last line> [replacement data (optional)]
# Accepts the same values for indexes as 'lreplace' (check your manual)
proc replaceLines {args} {
if {[llength $args]>=3} {
foreach {file start end} $args break
set cmd [list lreplace [split [read [set f [open $file r]]] \n] $start $end]
close $f
if {[llength $args]>3} {lappend cmd [lindex $args 3]}
puts -nonewline [set f [open $file w]] [join [eval $cmd] \n]
close $f
} {
error "wrong # args: should be \"[lindex [info level 0] 0] file start end ?replacement?\""
}
}
...btw: line numbers are zero-based, like lists, meaning the first line is called "0"
might sound stupid, but i am supposed to open the file write before i do this and close after ... and do i require to use it in a while or just like that ...
# Fetch a single line
proc getLine {file line} {lindex [split [read [set f [open $file]]][close $f] \n] $line}
could you give me a write syntax cause ive been reading the manual on lreplace and trying to understand it but i am affraid my knowledge about this topic isn't what it supposed to be to understand the therms that are being used ?
so what is the input syntax for your script ? i always get funny out puts :/
Heh why do you obfuscate things so much? There's really nothing wrong with using a few more lines
Actually, in this case the "ubfuscation" was for a reason. If I were to store the contents of the file in a variable, the proc would require 2*[file size $file] to execute (because a copy of the data is passed along to the commands when variable substitution is performed (at least that's how it is in older tcl versions))
Ofloo wrote:could you give me a write syntax cause ive been reading the manual on lreplace and trying to understand it but i am affraid my knowledge about this topic isn't what it supposed to be to understand the therms that are being used ?
so what is the input syntax for your script ? i always get funny out puts :/
I wrote a line on how to use the last two procs (re-read my post). There might be bugs in my code though (I didn't test it iirc ) Give me a example of what you're doing and what you expect as a result and I'll try to help you on the right track