简体   繁体   中英

How to match a word in particular line of afile using TCL regexp

Let consider i have one file ip.txt:

IP Address: 192.168.0.100/24 GW: 192.168.0.1
IP Address: 192.169.0.100/24 GW: 192.169.0.1
IP Address: 192.170.0.100/24 GW: 192.170.0.1

The above three lines are content in ip.txt. From that file i want to match Gw Ip address on the second line 192.169.0.1 by line basis using TCL regexp. Please anyone help me to get idea. thanks in advance

Read and discard the first line. If line 2 matches you are done otherwise terminate.

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

Of course, maybe its not always line 2 and it would be smarted to arrange it to close the file but the above is the simplest version in tcl that will meet the spec provided. The opened file gets closed on process exit. We don't need a regexp -- string match will do fine. Alternatively:

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

If I've understood what you're looking for correctly, you want the IP address part (specifically the gateway address) from the second line that matches some pattern? The easiest way is probably to parse the whole file in Tcl and then pick the value out of that (because the chances are that if you want the second value, you'll want the third later on).

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

Like that, you can parse in the file and poke through it at your leisure, even going back and forth in multiple passes, without having to keep the file open or reread it frequently. The split \\n / read idiom works well even with a file a few megabytes in size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM