【问题标题】:tcl insert string at certain line in filetcl 在文件的某一行插入字符串
【发布时间】:2021-11-19 09:14:43
【问题描述】:

我想在某一行插入一个字符串,我知道行号。

例如

#Aa_version = Aa/45.21-a32_1
#Aa_version = Aa/47.21-a33_1
Aa_version = Aa/45.27-a57_2 ->I can get this line number n

我想在第 n+1 行插入一行 Aa/49.27-a54_1

然后输入Aa_version = Aa/45.27-a57_2 -> #Aa_version = Aa/45.27-a57_2

输出是这样的

#Aa_version = Aa/45.21-a32_1
#Aa_version = Aa/47.21-a33_1
#Aa_version = Aa/45.27-a57_2
Aa_version = Aa/49.27-a54_1

我的代码是

set Aa ""
set fp [open $file "r+"]
set lines [split [read $fp] \n]
set idx [lsearch -regexp $lines {^Aa_version} ]
regexp {Aa(.+)} [lindex $lines $idx] Aa_version
set old_version "#$Aa_version"
set newAa [gets stdin]
set new_version "Aa_version =$newAa " 
puts $old_version ->replace $Aa_version
puts $new_version
close $fp

我怎样才能把它们放在正确的行 谢谢

【问题讨论】:

    标签: insert tcl


    【解决方案1】:

    我认为一次处理一行输入文件并依次查看每个文件而不是一次性读取所有文件然后在列表中查找、更改和插入元素更容易和更简洁:

    set fp [open $file]
    while {[gets $fp line] >= 0} {
        # If the line starts with Aa_version...
        if {[string match "Aa_version*" $line]} {
            # Comment it out
            puts "#$line"
            # And read the new version and write it out
            set newAa [gets stdin]
            puts "Aa_version = $newAa"
            # Copy the rest of the file to standard output and exit the loop
            chan copy $fp stdout
            break
        } else {
            puts $line
        }
    }
    close $fp
    

    但如果您想保留当前基于列表的方法,lreplace 是您的朋友:

    set fp [open $file]
    set lines [split [read $fp] \n]
    close $fp
    set idx [lsearch -glob $lines "Aa_version*"]
    # If a match was found...
    if {$idx >= 0} {
        # Read the new verson
        set newAa [gets stdin]
        # Replace the version element with two new elements:
        # Commented out previous version, and new version
        set lines [lreplace $lines $idx $idx \
                       "#[lindex $lines $idx]" "Aa_version = $newAa"]
    }
    puts [join $lines \n]
    

    【讨论】:

    • 嗨,肖恩,感谢您的帮助。我已经通过你的回答解决了这个问题。谢谢!!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 2015-12-28
    • 2016-08-20
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多