TCL: can foreach use with regexp

In Tcl, the foreach command is used to iterate over elements in a list, not individual lines in a string. To process each line of your text and perform the desired transformation, you can use the split command to split the text into lines and then iterate over them using foreach.

Here’s an example of how you can modify your code to achieve the desired result:

set txt {
    ITEM=a1
    *TYPE
    ITEM=a2
    *TYPE
}

set result ""
set lines [split $txt "\n"]
set numLines [llength $lines]

for {set i 0} {$i < $numLines} {incr i} {
    set line [lindex $lines $i]

    if {[regexp {ITEM=(.*)} $line match a]} {
        append result $line "\n"
        if {$i+1 < $numLines && [lindex $lines $i+1] eq "*TYPE"} {
            append result "*TYPE, ADD=$a\n"
        }
    } else {
        append result $line "\n"
    }
}

puts $result

This code will give you the following output:

graphql
Copy code
ITEM=a1
*TYPE, ADD=a1
ITEM=a2
*TYPE, ADD=a2

Note that in the foreach loop, I’ve replaced the regexp command with a simple pattern match using {ITEM=(.*)} since you only need to match the ITEM lines. The subsequent logic appends the required lines to the result variable based on the pattern match.

I hope this helps you achieve your desired result. Let me know if you have any further questions!

Live example: onecompiler.com/tcl/3z9rqbr76

Read more here: Source link