首页 > 解决方案 > 需要在 TCL 中 cat 多个文件

问题描述

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

下面是我的猫脚本,但似乎没有工作。

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

标签: appendtclcat

解决方案


我敢打赌“似乎没有工作”意味着您只看到$dir2/ABC1.shin的内容final.sh(或者可能看到您正在写入的部分内容$fir1/1.txt,而不是所有数据)。如果是这样,您将遇到缓冲问题,尝试$dir/1.txt在关闭或刷新之前读取infile。数据尚未写入基础文件。

为了将多个文件连接成一个文件,而不是依赖于外部程序cat(例如,您如何将参数引用到exec....),我将使用来自 tcllib的fileutil模块中的各种例程纯粹做tcl

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

如果您有大文件并且不想将它们全部保存在内存中(或者不想/不能安装 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

推荐阅读