Search code examples
regextclregexp-replace

In Tcl, how to read in file by line and find a list of string (from another file) then append the line with a ##


I need to be able tp read in file by line and find a set of strings (from another file) that starts with the strings plus set of characters like ({ somedata }) then append the line with a ## to that block.

Here is what I have so far:

set mydir <path to my dir>
#file name file.txt with content:
~>cat file.txt
Strng00  {
   some data 
}

Strng021  {
   some data 
}

Strng02  {
   some data 
}

Strng03  {
   some data 
}

Strng_dt  {
   some data 
}

Strng01 {
   some data 
}
Strng02  {
   some data 
}

Strng03  {
   some data 
}

Strng_dt  {
   some data 
}

Strng42  {
   some data 
}

Strng412 
-- 
set list { Strng01 Strng02 Strng03 Strng_dt Strng42 } # May be read in the list from another file which needs to be matched
set fileIn [lindex $argv 0]
set fileInId  [open $mydir/file.txt r]
set appendLine 0
foreach item $list {
    set j 0
    while {[gets $fileInId line ] != -1} {
        if [regexp  -all -line $item $line] { set appendLine 1 } 
        if $appendLine {
            if [regexp {^\s*\}\s*$} $line] { set appendLine 0 }   
            set line "## $line"    
        }
        puts $line
    }
set j 1
}

The result only shows the first entry of the list:

Strng00 
Strng021 
Strng02 
Strng03 
Strng_dt 
##Strng01  {
##   some data  
##}

Strng02 
Strng03 
Strng_dt 
Strng42 

Strng412

I'd like to get ## after each of the items listed.. Thanks in advance.`


Solution

  • Here's another take:

    while {[gets $fh line] != -1} {
        set first [lindex [split [string trimleft $line]] 0]
        puts [format "%s%s" [expr {$first in $list ? "##" : ""}] $line]
    }
    

    That finds the first word in the line, and checks if it is an element in $list.