gpt4 book ai didi

tcl - 使用 tcl 在文件中的 n 行之后插入代码行

转载 作者:行者123 更新时间:2023-12-04 14:13:52 25 4
gpt4 key购买 nike

我正在尝试编写一个 tcl 脚本,我需要在找到正则表达式后插入一些代码行。例如,我需要在找到当前文件中最后一次出现的#define 后插入更多#define 代码行。

谢谢!

最佳答案

当对文本文件进行编辑时,您将其读入并在内存中对其进行操作。由于您正在处理该文本文件中的代码行,我们希望将文件的内容表示为字符串列表(每个字符串都是一行的内容)。然后让我们使用 lsearch(使用 -regexp 选项)找到插入位置(我们将在反向列表上执行此操作,以便找到 最后一个 而不是第一个位置),我们可以使用 linsert 进行插入。

总的来说,我们得到的代码有点像这样:

# 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 < 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

在 Tcl 8.5 之前,样式有一点变化:

# 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

搜索所有索引(并将一个添加到最后一个索引)是足够合理的,但是插入的扭曲非常难看。 (8.4 之前?升级。)

关于tcl - 使用 tcl 在文件中的 n 行之后插入代码行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11281151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com