我有一個包含數千行的檔案,格式如下:
1.3.111.2.802.1.1.3.1.6.3.1.2.5.1.2 2 5
uj5u.com熱心網友回復:
這使用正則運算式來捕獲最后一個點之后的數字,而不是splits 和lindexs
set in [open $inputfile r]
set out [open $output w]
while {[gets $in line] != -1} {
if {[string match {CKSUM*} $line]} then continue
# capture the digits following the last dot
if {[regexp {.*\.(\d )} $line -> key] && 0 <= $key && $key <= 8919} {
puts $out $line
}
}
close $in
close $out
uj5u.com熱心網友回復:
好吧,在這種情況下,我們可以嘗試將每一行視為一個串列;這些行似乎已經足夠好了(第一個欄位是 OID 嗎?)
while {[gets $inChannel line] >= 0} {
if {[llength $line] <= 1 || [tcl::mathop::<= 0 [lindex $line end] 8191]} {
puts $outChannel $line
}
}
這里棘手的一點是使用tcl::mathop::<=,它是<=運算式運算子的命令形式,它允許我們檢查值(從該行的最后一個單詞開始)是否在 0 到 8191 的范圍內,而無需重復我們自己。
更謹慎的方法是:
while {[gets $inChannel line] >= 0} {
if {[catch {llength $line} length] || $length <= 1} {
# Ill-formed and short lines get copied
puts $outChannel $line
continue
}
set value [lindex $line end]
if {![string is integer -strict $value]} {
# Lines with non-integers get copied
puts $outChannel $line
continue
}
if {[tcl::mathop::<= 0 $value 8191]} {
# Lines with values in range get copied
puts $outChannel $line
}
}
可以不重復,puts但我認為生成的代碼不太清楚。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/461373.html
