Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When making edits to a text file, you read it in and operate on it in memory. Since you're dealing with lines of code in that text file, we want to represent the file's contents as a list of strings (each of which is the contents of a line). That then lets us use <code>lsearch</code> (with the <code>-regexp</code> option) to find the insertion location (which we'll do on the reversed list so we find the <em>last</em> instead of the first location) and we can do the insertion with <code>linsert</code>.</p> <p>Overall, we get code a bit like this:</p> <pre><code># Read lines of file (name in “filename” variable) into variable “lines” set f [open $filename "r"] set lines [split [read $f] "\n"] close $f # Find the insertion index in the reversed list set idx [lsearch -regexp [lreverse $lines] "^#define "] if {$idx &lt; 0} { error "did not find insertion point in $filename" } # Insert the lines (I'm assuming they're listed in the variable “linesToInsert”) set lines [linsert $lines end-$idx {*}$linesToInsert] # Write the lines back to the file set f [open $filename "w"] puts $f [join $lines "\n"] close $f </code></pre> <p>Prior to Tcl 8.5, the style changes a little:</p> <pre><code># Read lines of file (name in “filename” variable) into variable “lines” set f [open $filename "r"] set lines [split [read $f] "\n"] close $f # Find the insertion index in the reversed list set indices [lsearch -all -regexp $lines "^#define "] if {![llength $indices]} { error "did not find insertion point in $filename" } set idx [expr {[lindex $indices end] + 1}] # Insert the lines (I'm assuming they're listed in the variable “linesToInsert”) set lines [eval [linsert $linesToInsert 0 linsert $lines $idx]] ### ALTERNATIVE # set lines [eval [list linsert $lines $idx] $linesToInsert] # Write the lines back to the file set f [open $filename "w"] puts $f [join $lines "\n"] close $f </code></pre> <p>The searching for all the indices (and adding one to the last one) is reasonable enough, but the contortions for the insertion are pretty ugly. (Pre-8.4? Upgrade.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload