heyhey
heyhey

Reputation: 301

How can you drop lines in a parsed file in tcl

I have parsed a file in tcl and i read the line like that :

while {[gets $thefile line] >= 0} { ...

and i search my pattern like that

   if { [regexp {pattern} $line] } { ...

I want to store the line n+2 in a variable, how i can do that (i can't try to find a pattern in the next lines, because it is always changing)?

Thanks a lot

Upvotes: 0

Views: 131

Answers (2)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

You can build up your pattern space as a list at run-time. For example:

set lines {}
set file [open /tmp/foo]
while { [gets $file line] >=0 } {
    if { [llength $lines] >= 3 } {
        set lines [lrange $lines 1 2]
    }
    lappend lines $line
    if { [llength $lines] >= 3 } {
        puts [join $lines]
    }
}

After the third pass through the loop, lines will always hold the three most recent lines. In my sample, output looks like this:

line 1 line 2 line 3
line 2 line 3 line 4
line 3 line 4 line 5
line 4 line 5 line 6
line 5 line 6 line 7
line 6 line 7 line 8
line 7 line 8 line 9

You can then search lines inside the loop with your regular expression.

Upvotes: 0

Donal Fellows
Donal Fellows

Reputation: 137567

The simplest method would be to put an extra gets inside the if body:

while {[gets $thefile line] >= 0} {
    # ...
    if { [regexp {pattern} $line] } {
        if {[gets $thefile secondline] < 0} break
        # Now $line is the first line, and $secondline is the one after
    }
    # ...
}

Upvotes: 1

Related Questions