Foreach输出到文件中

时间:2017-03-16 23:51:14

标签: tcl

这是我试过的代码

foreach_in_collection t1 [ ga ...] {
    set f1 [ga $t1 type_name]
    set f2 [ga $t1 bb]
    puts $f1
    puts $f2
    puts $file1 $f1 $f2
}

我想将两个输出$ f1和$ f2写入$ file1,请告诉我 以上放$ file1 [list $ f1 $ f2]也行不通..

2 个答案:

答案 0 :(得分:0)

试试这个:

set fd [open out.txt w]
foreach {x y} [list a b c d e] {
  puts x=$x
  puts y=$y
  puts $fd $x
  puts $fd $y
}
close $fd

输出文件(之前):

$ cat out.txt
cat: out.txt: No such file or directory
$ 

执行输出:

$ tclsh foo.tcl
x=a
y=b
x=c
y=d
x=e
y=
$ 

输出文件(之后):

$ cat out.txt
a
b
c
d
e

$ 

答案 1 :(得分:0)

Sharad的解决方案非常完美。如果你想尝试,还有一种方法。

SBORDOLO-M-V1VG:实验sbordolo $ cat a11

 exec rm -rf out1.txt ;# No need to worry about file is there or not.
 exec touch out1.txt
 exec chmod 777 out1.txt ;#You can give a write permission here. I have given 777 just like that

 foreach {x y} [list a b c d e f] {
   puts x=$x
   puts y=$y
   exec echo $x >> out1.txt 
   exec echo $y >> out1.txt 

 }

运行脚本时: SBORDOLO-M-V1VG:实验sbordolo $ tclsh a11

x=a
y=b
x=c
y=d
x=e
y=f

SBORDOLO-M-V1VG:EXPERIMENT sbordolo $ cat out1.txt

a
b
c
d
e
f