heyhey
heyhey

Reputation: 301

How to copy a selection of lines from file to file in Tcl?

I want to copy a selection of lines from a file to another file in Tcl, where regular expressions find the starting and finishing lines of the selection. I tried this:

    while {[gets $thefile line] >= 0} {
       if { [regexp {pattern1} $line] } {
            while { [regexp {pattern2} $line] != 1 } {
                    puts $thefile2 $line
                    }
    }

The pattern1 and pattern2 are not always at the same line. this is an infinite loop, but how to continue to wrote the lines until the second pattern is reached ?

Thanks

Upvotes: 1

Views: 1596

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

There are two ways. Either you nest loops (with an inner one copying) or you have some kind of flag to switch the behavior back and forth of a single loop.

Nested loops

while {[gets $thefile line] >= 0} {
    if {[regexp {pattern1} $line]} {
        while {![regexp {pattern2} $line]} {
            puts $thefile2 $line
            # Note: might attempt a [gets] *twice* on EOF
            if {[gets $thefile line] < 0} break
        }
    }
}

Single loop

set flag off
while {[gets $thefile line] >= 0} {
    if {!$flag && [regexp {pattern1} $line]} {
        set flag on
    } elseif {$flag && [regexp {pattern2} $line]} {
        set flag off
    }

    # "off" and "on" are booleans
    if {$flag} {
        puts $thefile2 $line
    }
}

You might be able to simplify the code to switch modes by removing the tests for whether the flag is set or not at that point; you only have to be careful if the same line could be matched by both patterns.

Upvotes: 2

Related Questions