TCL:递归搜索子目录以获取所有 .tcl 文件

标签 tcl

我有一个主要的 TCL proc,它在其他文件夹和后续子目录中提供大量其他 tcl proc。例如,在主过程中它有:

source $basepath/folderA/1A.tcl
source $basepath/folderA/2A.tcl
source $basepath/folderA/3A.tcl
source $basepath/folderB/1B.tcl
source $basepath/folderB/2B.tcl
source $basepath/folderB/3B.tcl

当我总是知道我将在文件夹 A 和文件夹 B 中获取所有内容时,这样做似乎有点愚蠢。是否有一个函数(或简单的方法)可以让我只获取整个文件夹中的所有 .tcl 文件?

最佳答案

基于拉曼曼的回复,这里有一个例程,它使用内置的 TCL 文件命令解决问题,并以递归方式在目录树中向下工作。

# findFiles
# basedir - the directory to start looking in
# pattern - A pattern, as defined by the glob command, that the files must match
proc findFiles { basedir pattern } {

    # Fix the directory name, this ensures the directory name is in the
    # native format for the platform and contains a final directory seperator
    set basedir [string trimright [file join [file normalize $basedir] { }]]
    set fileList {}

    # Look in the current directory for matching files, -type {f r}
    # means ony readable normal files are looked at, -nocomplain stops
    # an error being thrown if the returned list is empty
    foreach fileName [glob -nocomplain -type {f r} -path $basedir $pattern] {
        lappend fileList $fileName
    }

    # Now look for any sub direcories in the current directory
    foreach dirName [glob -nocomplain -type {d  r} -path $basedir *] {
        # Recusively call the routine on the sub directory and append any
        # new files to the results
        set subDirList [findFiles $dirName $pattern]
        if { [llength $subDirList] > 0 } {
            foreach subDirFile $subDirList {
                lappend fileList $subDirFile
            }
        }
    }
    return $fileList
 }

关于TCL:递归搜索子目录以获取所有 .tcl 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/429386/

相关文章:

javascript - 口译员和安全口译员有什么区别?

css - 如何在 tcl tk GUI 中通过调整窗口大小来调整窗口内的框架、标签、文本等小部件的大小

for-loop - 打破 tcl 中的父循环

unicode - 如何在 Tkinter 中打印非 BMP Unicode 字符(例如 𝄫)

regex - 使用 & 将 regsub 中的匹配传递给过程(正在使用 Tcl)

ssl - (Tcl) 通过 gmail 和 yahoo 邮件服务器发送电子邮件

buffer - 禁用 Tcl 的输入缓冲?

syntax - 为什么 Tcl 在调用 "set"时不在变量名前使用美元符号?

namespaces - Tcl命名空间定义

regex - 如何在 tcl 中检查和替换非 UTF-8 字符?