n00*_*mer 4 replace file tcl line
假设我打开了一个文件,然后将其解析为行.然后我用一个循环:
foreach line $lines {}
Run Code Online (Sandbox Code Playgroud)
在循环内部,对于某些行,我想用不同的行替换它们在文件中.可能吗?或者我必须写入另一个临时文件,然后在我完成后替换文件?
例如,如果文件包含
AA
BB
Run Code Online (Sandbox Code Playgroud)
然后我用小写字母替换大写字母,我想要包含原始文件
aa
bb
Run Code Online (Sandbox Code Playgroud)
谢谢!
对于纯文本文件,最安全的做法是将原始文件移动到"备份"名称,然后使用原始文件名重写它:
更新:根据Donal的反馈进行编辑
set timestamp [clock format [clock seconds] -format {%Y%m%d%H%M%S}]
set filename "filename.txt"
set temp $filename.new.$timestamp
set backup $filename.bak.$timestamp
set in [open $filename r]
set out [open $temp w]
# line-by-line, read the original file
while {[gets $in line] != -1} {
#transform $line somehow
set line [string tolower $line]
# then write the transformed line
puts $out $line
}
close $in
close $out
# move the new data to the proper filename
file link -hard $filename $backup
file rename -force $temp $filename
Run Code Online (Sandbox Code Playgroud)
除了格伦的回答.如果您希望在整个内容的基础上对文件进行操作并且文件不是太大,那么您可以使用fileutil :: updateInPlace.这是一个代码示例:
package require fileutil
proc processContents {fileContents} {
# Search: AA, replace: aa
return [string map {AA aa} $fileContents]
}
fileutil::updateInPlace data.txt processContents
Run Code Online (Sandbox Code Playgroud)