在tcl中,如何替换文件中的一行? [英] in tcl, how do I replace a line in a file?

查看:1106
本文介绍了在tcl中,如何替换文件中的一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我打开了一个文件,然后将其解析为几行.然后我使用一个循环:

foreach line $lines {}

在循环内部,对于某些行,我想用不同的行替换它们.是否有可能?还是我必须写入另一个临时文件,然后在完成后替换这些文件?

例如,如果文件包含

AA
BB

然后我将大写字母替换为小写字母,我希望原始文件包含

aa
bb

谢谢!

解决方案

对于纯文本文件,将原始文件移动到备份"名称然后使用原始文件名重写是最安全的:

更新:根据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 

let's say I opened a file, then parsed it into lines. Then I use a loop:

foreach line $lines {}

inside the loop, for some lines, I want to replace them inside the file with different lines. Is it possible? Or do I have to write to another temporary file, then replace the files when I'm done?

e.g., if the file contained

AA
BB

and then I replace capital letters with lower case letters, I want the original file to contain

aa
bb

Thanks!

解决方案

for plain text files, it's safest to move the original file to a "backup" name then rewrite it using the original filename:

Update: edited based on Donal's feedback

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 

这篇关于在tcl中,如何替换文件中的一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆