Juan J. Cepeda
Juan J. Cepeda

Reputation: 1

Extract information from two different files using tcl

I want to extract data from two different files. The problem that I had is that I can't write this information as a separate columns. I mean when I extract the info from the 2nd file and write on the output it writes as a continuation of the first column.

      set input1 [open "dat1.txt" r]
      set input2 [open "dat2.txt" r] 
      set out [open "final.txt" w]
while { [gets $input1 line1] >= 0 } {
   
   if {[string range $line1 0 3] == "ENE "} {
      puts $out "[expr [lindex $line1 4]]"
   }
}
while { [gets $input2 line2] >= 0 } {
   set v [lindex $line2 1]
   puts $out "$v"
}

close $input1
close $input2
close $out

Upvotes: 0

Views: 202

Answers (2)

glenn jackman
glenn jackman

Reputation: 246744

I think what you're asking to do is read a line from input1 and a line from input2 and combine them somehow.

Given

$ cat dat1.txt
ENE . . . a
ENE . . . b
ENE . . . c

$ cat dat2.txt
41
42
43

Then

set input1 [open dat1.txt r]
set input2 [open dat2.txt r]
#                                         
while {[gets $input1 line1] >= 0 && [gets $input2 line2] >= 0} {
    if {[string match "ENE *" $line1]} {
        puts "[lindex [split $line1] 4] $line2"
    }
}

outputs

a 41
b 42
c 43

Upvotes: 0

Colin Macleod
Colin Macleod

Reputation: 4372

I'm going to assume that what you want is for each line of output to have one value from dat1 followed by one value from dat2. In that case you could do something like this (omitting the opens and closes which stay the same):

while { [gets $input1 line1] >= 0 } {
   if {[string range $line1 0 3] == "ENE "} {
      lappend list1 [expr [lindex $line1 4]]
   }
}
while { [gets $input2 line2] >= 0 } {
   lappend list2 [lindex $line2 1]
}
foreach val1 $list1 val2 $list2 {
   puts $out "$val1 $val2"
}

Upvotes: 0

Related Questions