Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multiple lines from a file using TCL?

Tags:

tcl

How do I read more than a single line in a file using tcl? That is by default the gets command reads till a new line is found, how do I change this behaviour to read a file till a specific character is found?

like image 224
user1702234 Avatar asked Jul 06 '26 03:07

user1702234


1 Answers

If you don't mind reading over a bit, you can do it by looping with gets or read in a loop:

set data ""
while {[gets $chan line] >= 0} {
    set idx [string first $whatToLookFor $line]
    if {$idx == -1} {
        append data $line\n
    } else {
        # Decrement idx; don't want first character of $whatToLookFor
        append data [string range $line 0 [incr idx -1]]
        break
    }
}
# Data has everything up to but not including $whatToLookFor

If you're looking for multiline patterns, I suggest reading the whole file into memory and working on that. It's just so much easier than trying to write a correct matcher:

set data [read $chan]
set idx [string first $whatToLookFor $data]
if {$idx > -1} {
    set data [string range $data 0 [incr idx -1]]
}

This latter form will also work just fine with binary data. Just remember to fconfigure $chan -translation binary first if you're doing that.

like image 78
Donal Fellows Avatar answered Jul 14 '26 06:07

Donal Fellows



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!