在TCL中的文件中的特定位置插入文本

时间:2015-10-13 14:44:00

标签: tcl

我的任务是在TCL脚本的文件中的任何给定位置插入文本。

我试过的是:

set a [open "C:/TAT_DATA/temp.txt" a+]
seek $a -8 end
puts $a "insert between"
close $a

但它正在取代/覆盖现有内容。我可以做别的吗? 我不想阅读整个文件内容。

2 个答案:

答案 0 :(得分:0)

这可能是其中一种方式:

set a [open "C:/TAT_DATA/temp.txt" a+]
#go to the specific position
seek $a -9 end
#read the data till end
set data [read $a]
#again move pointer to previous position
seek $a -9 end
#insert data (along with the previous data overwriting the existing data)
puts $a "insert between $data"
close $a

答案 1 :(得分:0)

package require fileutil
namespace import fileutil::*

set filename "C:/TAT_DATA/temp.txt"
set pos [expr {[file size $filename] - 9}]
insertIntoFile $filename $pos "insert between"

fileutil模块中的命令非常有用。您可以在一个命令中设置文件的内容:

writeFile $filename foobarfoobar

看内容:

cat $filename
# -> foobarfoobar

添加更多内容:

appendToFile $filename baz
# file contents: foobarfoobarbaz

插入内容:

insertIntoFile $filename 6 123456
# file contents: foobar123456foobarbaz

删除内容:

removeFromFile $filename 7 4
# file contents: foobar16foobarbaz

替换内容:

replaceInFile $filename 6 2 --==--
# file contents: foobar--==--foobarbaz

或使用命令处理内容:

writeFile $filename "a b c"
proc foo data {
    foreach item $data {
        lappend res ($item)
    }
    join $res -
}
updateInPlace $filename foo
# file contents: (a)-(b)-(c)

文档:exprfilefileutil包,foreachjoinlappendnamespace,{{ 3}},packageproc

相关问题