需要在TCL中cat多个文件

Need to cat multiple files in TCL

我想将 2 个文件分类或合并在一起。使用 exec cat 还是 append 更好?

下面是我的 cat 脚本,但似乎没有用。

set infile [open "$dir/1.txt" w+]

puts $infile "set a 1"
puts $infile "set b 2"

exec /bin/cat "$dir/1.txt $dir2/ABC1.sh" > final.sh

close $infile

我敢打赌“似乎不起作用”意味着您只能在 final.sh 中看到 $dir2/ABC1.sh 的内容(或者可能会看到您正在写给 $fir1/1.txt,并非所有数据)。如果是这样,您 运行 陷入了缓冲问题,尝试在关闭或刷新 infile 之前读取 $dir/1.txt 就像您一样。数据还没有写入底层文件

用于将多个文件连接成一个文件,而不是依赖像 cat 这样的外部程序(您引用 exec 的参数的方式也可能存在问题...) ,我将使用来自 tcllib 的 fileutil 模块中的各种例程来纯 tcl:

package require fileutil
fileutil::writeFile final.sh [fileutil::cat -- $dir/1.txt $dir2/ABC1.sh]

如果您有大文件并且不想将它们全部保存在内存中(或者不想to/can不安装 tcllib),chan copy 也可以:

set outfile [open final.sh w]
foreach file [list $dir/1.txt $dir2/ABC1.sh] {
    set sourcefile [open $file r]
    chan copy $sourcefile $outfile
    close $sourcefile
}
close $outfile