[英]How to match a word in particular line of afile using TCL regexp
假設我有一個文件ip.txt:
IP地址:192.168.0.100/24 GW:192.168.0.1
IP地址:192.169.0.100/24 GW:192.169.0.1
IP地址:192.170.0.100/24 GW:192.170.0.1
以上三行是ip.txt中的內容。 我想從該文件中使用TCL正則表達式192.169.0.1
匹配second line
192.169.0.1
上的Gw IP地址。 請任何人幫助我獲得想法。 提前致謝
讀取並丟棄第一行。 如果第2行匹配,則完成操作,否則終止。
set f [open $filename r]
if {[gets $f line] == -1} { return -code error "failed to read line 1" }
if {[gets $f line] == -1} { return -code error "failed to read line 2" }
if {![string match "*GW: 192.169.0.1*" $line]} { return -code error "failed to match" }
return
當然,也許它並不總是第2行,並且安排它關閉文件會很聰明,但是以上是tcl中最簡單的版本,可以滿足所提供的規范。 打開的文件在進程退出時關閉。 我們不需要正則表達式-字符串匹配就可以了。 或者:
set f [open $filename r]
set lineno 1
while {[gets $f line] != -1 && $lineno < 3} {
if {$lineno == 2 && [regexp {GW: 192.169.0.1} $line]} {
return 1
}
incr lineno
}
close $f
return 0
如果我正確理解了您要尋找的內容,那么您想要第二行的IP地址部分(特別是網關地址)與某種模式匹配嗎? 最簡單的方法可能是在Tcl中解析整個文件,然后從中選擇值(因為如果您想要第二個值,則稍后需要第三個值)。
proc parseTheFile {filename} {
set f [open $filename]
set result {}
foreach line [split [read $f] "\n"] {
if {[regexp {IP Address: ([\d.]+)/(\d+) GW: ([\d.]+)} $line -> ip mask gw]} {
lappend result [list $ip $mask $gw]
}
}
close $f
return $result
}
set parsed [parseTheFile "the/file.txt"]
set secondGW [lindex $parsed 1 2]
### Alternatively:
# set secondLineInfo [lindex $parsed 1]
# set secondGW [lindex $secondLineInfo 2]
### Or even:
# lassign [lindex $parsed 1] secondIP secondMask secondGW
這樣,您就可以解析文件並在閑暇時瀏覽它,甚至需要多次往返來回,而不必保持文件打開或頻繁重讀。 split \\n
/ read
成語split \\n
即使在文件大小為幾兆字節的情況下也能很好地工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.