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

时间:2017-05-05 07:33:45

标签: tcl

我想搜索一个单词" VPEM"如果发现与下一行交换它 比方说如果我们在19行交换第19行和第20行中找到VPEM

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

由于这是一个中等复杂的搜索和修改,我们应该将文件读入内存并在那里进行处理。鉴于此,我们可以使用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 {\yVPEM\y}] {
    # 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