![](/img/trans.png)
[英]How to delete lines matching a pattern from a file using Tcl/Expect
[英]How to delete a part of the text file if a pattern is found matching using tcl?
如果我搜索的模式匹配,如何刪除文本文件的一部分?
例如:
pg_pin (VSS) {
direction : inout;
pg_type : primary_ground;
related_bias_pin : "VBN";
voltage_name : "VSS";
}
leakage_power () {
value : 0;
when : "A1&A2&X";
**related_pg_pin** : VBN;
}
我的模式是related_pg_pin。 如果找到這種模式,我想刪除該特定部分(從泄漏功率(){直到結束括號}開始)。
proc getSection f {
set section ""
set inSection false
while {[gets $f line] >= 0} {
if {$inSection} {
append section $line\n
# find the end of the section (a single right brace, #x7d)
if {[string match \x7d [string trim $line]]} {
return $section
}
} else {
# find the beginning of the section, with a left brace (#x7b) at the end
if {[string match *\x7b [string trim $line]]} {
append section $line\n
set inSection true
}
}
}
return
}
set f [open data.txt]
set g [open output.txt w]
set section [getSection $f]
while {$section ne {}} {
if {![regexp related_pg_pin $section]} {
puts $g $section
}
set section [getSection $f]
}
close $f
close $g
從代碼的最后一段開始,我們打開一個文件進行讀取(通過$f
頻道),然后得到一個部分。 (獲取一個部分的過程有點復雜,所以它會進入一個命令過程。)只要非空部分不斷出現,我們檢查模式是否發生:如果沒有,我們打印通過通道$g
到輸出文件的部分。 然后我們得到下一部分並進入下一次迭代。
要獲得一個部分,首先假設我們還沒有看到部分的任何部分。 然后我們繼續讀取行,直到找到文件的末尾。 如果找到以左括號結尾的行,我們將其添加到該部分並記下我們現在在一個部分中。 從那時起,我們將每一行添加到該部分。 如果找到由單個右括號組成的行,我們退出該過程並將該部分傳遞給調用者。
文檔: ! (運算符) , > =(運算符) , 追加 , 關閉 , 獲取 , if , ne(運算符) , open , proc , puts , regexp , return , set , string , while , Tcl正則表達式的語法
Tcl字符串匹配的語法:
*
匹配零個或多個字符的序列 ?
匹配單個字符 [chars]
在由字符指定集合相匹配的單個字符(^ 並不否定;一個范圍可以被給定為AZ) \\x
匹配字符x ,即使該字符是特殊的( *?[]\\
) 這是一種“聰明”的方式:
proc unknown args {
set body [lindex $args end]
if {[string first "related_pg_pin" $body] == -1} {puts $args}
}
source file.txt
您的數據文件似乎與Tcl語法兼容,因此像Tcl文件一樣執行它,對於未知命令,請檢查“command”的最后一個參數是否包含您要避免的字符串。
這顯然是極其危險的,但它很有趣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.