Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a file with Tcl

Tags:

tcl

I have a file in here which has multiple set statements. However I want to extract the lines of my interest. Can the following code help

set in [open filename r]    
seek $in 0 start    
while{ [gets $in line ] != -1} {    
    regexp (line to be extracted)
}
like image 242
Naaz Avatar asked Sep 17 '25 02:09

Naaz


1 Answers

Other solution:

Instead of using gets I prefer using read function to read the whole contents of the file and then process those line by line. So we are in complete control of operation on file by having it as list of lines

set fileName [lindex $argv 0]
catch {set fptr [open $fileName r]} ;
set contents [read -nonewline $fptr] ;#Read the file contents
close $fptr ;#Close the file since it has been read now
set splitCont [split $contents "\n"] ;#Split the files contents on new line
foreach ele $splitCont {
    if {[regexp {^set +(\S+) +(.*)} $ele -> name value]} {
        puts "The name \"$name\" maps to the value \"$value\""
    }
}

How to run this code:
say above code is saved in test.tcl
Then

tclsh test.tcl FileName

FileName is full path of file unless the file is in the same directory where the program is.

like image 55
vaichidrewar Avatar answered Sep 23 '25 07:09

vaichidrewar