【问题标题】:Tcl. Replace string in fileTcl。替换文件中的字符串
【发布时间】:2016-08-20 20:40:07
【问题描述】:

tcl 中有一个命令允许在现有的基础上通过替换创建新字符串:

string map ?-nocase? mapping string

tcl 中是否有允许更改现有字符串的命令? 例如:

set string1 abcabcabc

通过使用一些命令将字母“a”替换为“0”,得到值为0bc0bc0bc的string1

【问题讨论】:

    标签: string dictionary replace tcl


    【解决方案1】:

    尽管@peter 解决方案运行良好。

    要替换文件TCL 中的string 而不使用fileutil 包:

    set fd [open "filename.txt" r]
    set newfd [open "filename.txt.tmp" w]
    while {[gets $fd line] >= 0} {
        set newline [string map {a 0} $line]
        puts $newfd $newline
    }
    
    close $fd
    close $newfd
    file rename -force "filename.txt.tmp" "filename.txt"
    

    【讨论】:

    • set f [open file.txt r+] ; puts -nonewline $f [string map {a 0} [read $f]][seek $f 0;list] ; close $f ;) 也可以,但我不建议将它用于生产代码。
    • @PeterLewerin “不会推荐它用于生产代码”——你可以再说一遍!虽然它确实具有故障安全性,但很容易引入错字并使其不真实。 OTOH, 值得考虑一次转换文件全部内容的方法。即使是数兆字节的文件,也很容易以这种方式处理。
    【解决方案2】:
    % set string1 abcabcabc
    abcabcabc
    % set string1 [string map {a 0} $string1]
    0bc0bc0bc
    

    在文件中替换(文件“file.txt”包含abcabcabc):

    % package require fileutil
    % ::fileutil::updateInPlace file.txt {string map {a 0}}
    % ::fileutil::cat file.txt
    0bc0bc0bc
    

    文档:fileutil 包、packagesetstring

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 2023-03-21
      • 2016-08-27
      • 1970-01-01
      相关资源
      最近更新 更多