Warm tip: This article is reproduced from serverfault.com, please click

TCL incr filename

发布于 2020-12-08 05:16:25

I do not want to set $outfile so many times, I would like to incr the filename. How do I do that in TCL?

set incr 1
set outfile [open "file$incr.txt" w]

set infile1 "[glob /a/b/c/d/a12b.txt /a/e/c/e/c123d.txt /e/e/d/e/2abd.txt ]"
set infile2 "[glob /a/b/c/d/a12b.txt /a/e/c/e/c123d.txt /e/e/d/e/2abd.txt ]"
set infile3 "[glob /a/b/c/d/a12b.txt /a/e/c/e/c123d.txt /e/e/d/e/2abd.txt ]"

foreach infile $infiles$incr {

    puts $oufile$incr "testing"

}

However , my above code , does not seem to work?

Questioner
Kimi
Viewed
11
Mkn 2020-12-08 17:42:48

With incr function :

set infile {}
set i 0

lappend infile "[glob /a/b/c/d/a12b.txt /a/e/c/e/c123d.txt /e/e/d/e/2abd.txt ]"
lappend infile "[glob /a/b/c/d/a12b.txt /a/e/c/e/c123d.txt /e/e/d/e/2abd.txt ]"
lappend infile "[glob /a/b/c/d/a12b.txt /a/e/c/e/c123d.txt /e/e/d/e/2abd.txt ]"

foreach value $infile {
    incr i
    set outfile [open "file${i}.txt" w]
    foreach files $value {
        puts $outfile "testing"
    }
    close $outfile
}

Another solution, you can use a array :

set infile(1) "[glob /a/b/c/d/a12b.txt /a/e/c/e/c123d.txt /e/e/d/e/2abd.txt ]"
set infile(2) "[glob /a/b/c/d/a12b.txt /a/e/c/e/c123d.txt /e/e/d/e/2abd.txt ]"
set infile(3) "[glob /a/b/c/d/a12b.txt /a/e/c/e/c123d.txt /e/e/d/e/2abd.txt ]"

foreach {key value} [array get infile] {
    set outfile [open "file${key}.txt" w]
    foreach files $value {
        puts $outfile "testing"
    }
    close $outfile

}