Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.7k views
in Technique[技术] by (71.8m points)

regex - Extract contents of line from file given the line number in TCL

I know this question has been asked in the context of perl and grep, but I'm wondering if this is possible using TCL.

Currently I'm using the scanmatch command to find a particular regex in a text file. I see that the array element matchInfo(linenum) provides the line number of the matched line. Given this line number as an index, I want to extract contents of subsequence lines.

I'm wondering if there is a function that allows line contents to be extracted by line number.

For reference, I am following this page http://www.ucolick.org/~de/book/scan.html

Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A read through that page indicates matchinfo(offset) would be most appropriate.

If you have

scanmatch $scanContext "some pattern" {nextLines 5 $fileName $matchinfo(offset)}

So nextLines could perhaps return the next number of lines. The magic here is the seek command to jump right to the line that matched.

proc nextLines {numLines fileName offset} {
    set fid [open $fileName r]
    seek $fid $offset
    for {set i 0} {$i < $numLines} {incr i} {
        if {[gets $fid line] == -1} break
        lappend lines $line
    }
    close $fid
    return $lines
}

You could experiment by passing $matchinfo(handle) instead of the filename, and reading the next few lines directly (without having to seek). However I don't know how scanfile will react if the position into the file is changed by some other code.


Just did some quick experimentation, and scanfile is not bothered if you read ahead in the scanmatch code. scanfile will pick up at the new location in the file. This would be similar to using getline in awk code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...