如何使用 Tcl/Expect 从文件中删除与模式匹配的行
How to delete lines matching a pattern from a file using Tcl/Expect
我正在尝试了解如何使用 expect。
我想检查一个文件中是否有某个字符串,如果它确实包含它而不是删除整行,我知道我将如何使用 bash 和 if 和 grep 来做到这一点,但我相当新的期望,我在让它工作时遇到问题基本想法是这样的(在 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"
有关使用 catch
和 exec
的详细说明,请参阅 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"
由于@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"
我正在尝试了解如何使用 expect。
我想检查一个文件中是否有某个字符串,如果它确实包含它而不是删除整行,我知道我将如何使用 bash 和 if 和 grep 来做到这一点,但我相当新的期望,我在让它工作时遇到问题基本想法是这样的(在 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"
有关使用 catch
和 exec
更多当前的 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 删除了他的回答,这里有一个纯 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"