如何使用Tcl / Expect从文件中删除与模式匹配的行

时间:2017-06-27 04:43:56

标签: linux tcl expect

我想了解如何使用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 

提前致谢。

2 个答案:

答案 0 :(得分:1)

另一种方法:使用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"

有关使用catchexec

的详细说明,请参阅https://wiki.tcl.tk/1039#pagetoce3a5e27b

更多当前的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"

答案 1 :(得分:1)

由于@whjm删除了他的答案,这里有一个纯Tcl方式来完成你的任务:

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"