简体   繁体   中英

Search a section of text, which occurs regularly in tcl

I have a file called log_file with following text:

....some text....

line wire (1)

mode : 2pair , annex : a

coding : abcd

rate : 1024

status : up

....some text....

line wire (2)

mode : 4pair , annex : b

coding : xyz

rate : 1024

status : down

....some text....

The values may differ but the attributes are always the same. Is there a way to find each line wire and display their attributes? The number of line wires also may differ.

EDIT: File doesn't have any blank lines. There are more attributes but only these are needed. Can I get like the first "n" lines, instead of searching for every line? ie if there is line wire (1), copy that line plus the next 4 lines.

And I am copying the searched lines to a output file $fout , which I have used earlier in the script with the same $line .

Given your sample:

set fh [open log_file r]
while {[gets $fh line] != -1} {
    switch -glob -- $line {
        {line wire*} {puts $line}
        {mode : *}   -
        {coding : *} -
        {rate : *}   -
        {status : *} {puts "    $line"}
    }
}
close $fh

outputs

line wire (1)
    mode : 2pair , annex : a
    coding : abcd
    rate : 1024
    status : up
line wire (2)
    mode : 4pair , annex : b
    coding : xyz
    rate : 1024
    status : down

Edit: print the next "n" lines following the "line wire" line to a file

set in [open log_file r]
set out [open log_file_filtered w]
set n 4
while {[gets $in line] != -1} {
    if {[string match {line wire*} $line]} {
        puts $line
        for {set i 1} {$i <= $n} {incr i} {
            if {[gets $in line] != -1} {
                puts $out "    $line"
            }
        }
    }
}
close $fh

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