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

时间:2012-07-01 10:15:07

标签: tcl

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

谢谢!

3 个答案:

答案 0 :(得分:4)

在对文本文件进行编辑时,您将其读入并在内存中对其进行操作。由于您正在处理该文本文件中的代码行,因此我们希望将文件的内容表示为字符串列表(每个字符串都是行的内容)。然后,我们可以使用lsearch(使用-regexp选项)查找插入位置(我们将在反向列表中执行此操作,以便找到 last 而不是第一个位置)我们可以使用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之前?升级。)

答案 1 :(得分:3)

不完全是你的问题的答案,但这是为shell脚本提供的任务类型(即使我的解决方案有点难看)。

tac inputfile | sed -n '/#define/,$p' | tac
echo "$yourlines"
tac inputfile | sed '/#define/Q' | tac

应该有用!

答案 2 :(得分:0)

set filename content.txt
set fh [open $filename r]
set lines [read $fh]
close $fh


set line_con [split $lines "\n"]
set line_num {} 
set i 0
foreach line $line_con {
    if [regexp {^#define} $line] {
        lappend line_num $i
        incr i
    }
}

if {[llength $line_num ] > 0 } {
    linsert $line_con [lindex $line_num end] $line_insert
} else {
    puts "no insert point"
}


set filename content_new.txt
set fh [open $filename w]
puts $fh file_con
close $fh