如何在文件中搜索一个单词,并使用TCL与下一行交换包含该单词的行



我想搜索一个单词" vpem",如果找到了下一行说如果我们在19行交换线19和20

中找到VPEM

任何人都可以帮忙吗?

由于这是一个中等复杂的搜索和修饰,因此我们应该将文件读取到内存中并在此处进行处理。鉴于这一点,然后我们可以使用split来列出行列表,lsearch -all查找有趣的线,而lset实际进行交换。

# Read in; idiomatic
set f [open $theFile]
set lines [split [read $f] "n"]
close $f
# y is a word boundary constraint; perfect for what we want!
foreach idx [lsearch -all -regexp $lines {yVPEMy}] {
    # Do the swap; idiomatic
    set tmp [lindex $lines $idx]
    set i2 [expr {$idx + 1}]
    lset lines $idx [lindex $lines $i2]
    lset lines $i2 $tmp
}
# Write out; idiomatic
set f [open $theFile w]
puts -nonewline $f [join $lines "n"]
close $f

最新更新