regex - TCL parsing issue


Keywords:regex 


Question: 

Below is the content of my $file_path

if **{**[info exists ABC] && $ABC == "xyz"} **{**
    # constraints
    # TODO:
    echo "do something"
 }

I want the contents of this file to be printed as it is in dofile.tcl. But somehow with the below code begin and end open brackets "{" highligted in bold are getting omitted.

Result :

if [info exists ABC] && $ABC == "xyz"} **#Notice the missing { both in begin and end**
    # constraints
    # TODO:
    echo "do something"
 }

Code:

set fp [open "$file_path" r]
                set file_data [read $fp]
                close $fp
                echo "D1 : file data is $file_data" >> abc.log
                set data [split $file_data "\n"]
                foreach line $data {
                    echo "D2: Line is $line" >> abc.log
                    if { ! [regexp {^\#} $line] } {
                       echo "$line" >> dofile.tcl
                          }
                }

D1 prints the entire data with "{" as required while D2 omits "{"


1 Answer: 

Try using puts instead of echo, as in:

set lf [open "abc.log" w]
set tf [open "dofile.tcl" w]
set fp [open "$file_path" r]
set file_data [read $fp]
close $fp
puts $lf "D1 : file data is $file_data"
set data [split $file_data "\n"]
foreach line $data {
    puts $lf "D2: Line is $line"
    if { ! [regexp {^\#} $line] } {
       puts $tf "$line"
     }
}
close $lf
close $tf

My output looks like this:

if **{**[info exists ABC] && $ABC == "xyz"} **{**
    # constraints
    # TODO:
    echo "do something"
 }