如何使用TCL/Expect删除与文件匹配的线路



我正在尝试了解如何与期望一起工作。

我想检查一个文件中是否包含某个字符串,并且是否包含它,而不是删除整行,我知道如何使用IF和GREP进行bash,但是我对期望很新,我正在遇到问题的问题是(在bash脚本中(

if grep -q "string" "file";
then
    echo "something is getting deleted".
    sed -i "something"/d "file"
    echo Starting SCP protocol
else
    echo "something was not found"
    echo Starting SCP protocol. 
fi 

预先感谢。

另一种方法:将TCL用作胶水,例如shell,呼唤系统工具:

if {[catch {exec grep -q "string" "file"} output] == 0} {
    puts "something is getting deleted".
    exec sed -i "something"/d "file"
} else {
    puts "something was not found"
}
puts "Starting SCP protocol"

请参阅https://wiki.tcl.tk/1039#pagetoce3a5e27b,以详细说明使用catchexec

更多的当前TCL看起来像

try {
    exec grep -q "string" "file"
    puts "something is getting deleted".
    exec sed -i "something"/d "file"
} on error {} {
    puts "something was not found"
}
puts "Starting SCP protocol"

由于@whjm删除了他的答案,这是完成任务的纯粹方法:

set filename "file"
set found false
set fh [open $filename r]
while {[gets $fh line] != -1} {
    if {[regexp {string} $line]} {
        puts "something is getting deleted"
        close $fh
        set fh_in [open $filename r]
        set fh_out [file tempfile tmpname]
        while {[gets $fh_in line] != -1} {
            if {![regexp {something} $line]} {
                puts $fh_out $line
            }
        }
        close $fh_in
        close $fh_out
        file rename -force $tmpname $filename
        set found true
        break        
    }
}
if {!$found} {close $fh}
puts "Starting SCP protocol"

最新更新