使用 tcl glob 进行通配符搜索

Wildcard Search with tcl glob

我正在尝试搜索子目录中的目录和 return 匹配通配符 glob 搜索的任何目录。

文件夹结构如下所示...

Rootdir
 -dir01
   -dir_match_01-OLD
   -dir_match_01
 -dir02
   -dir_match_02-OLD
   -dir_match_02
 -dir03
   -dir_match_03-OLD
   -dir_match_03
 -...

我正在搜索位于 dir01、dir02、dir03 等目录中的目录。

我正在使用以下 glob 调用递归搜索目录,这似乎工作正常...

set rootdir "/home/rootdir/"
set searchstring "*-OLD"

foreach dir [glob -nocomplain -dir $rootdir -type d -- *] {
  set result [glob -nocomplain -dir $dir -type d -- $searchstring]
  puts $result
}

我发现的是,如果我不在 $searchstring 中使用通配符并使用存在的确切目录名称,我会成功接收输出。但是,如果我随后使用通配符搜索以 *-OLD 结尾的所有目录,它会成功找到它们并将它们全部放在同一行上。

/home/rootdir/dir01/directory01-OLD /home/rootdir/dir01/directory02-OLD /home/rootdir/dir01/directory03-OLD

我试图通过使用 regsub 将空格替换为 \n 来分隔条目,但它所做的只是删除空格...

/home/rootdir/dir01/directory01-OLD/home/rootdir/dir01/directory02-OLD/home/rootdir/dir01/directory03-OLD

对于我做错的任何建议将不胜感激,谢谢。

最明显的部分是glob总是returns一个名字列表。因此,您需要像这样执行最内层的循环:

foreach dir [glob -nocomplain -dir $rootdir -type d -- *] {
    foreach result [glob -nocomplain -dir $dir -type d -- $searchstring] {
        puts $result
    }
}

但是,对于固定深度搜索,我认为你可以这样做:

foreach dir [glob -nocomplain -dir $rootdir -type d -- */$searchstring] {
    puts $dir
}

如果需要递归(完整目录树)搜索,Tcllib 中有实用命令 fileutil package:

package require fileutil

proc myMatcher {pattern filename} {
    # Does the filename match the pattern, and is it a directory?
    expr {[string match $pattern $filename] && [file isdir $filename]}
}

set rootdir "/home/rootdir/"
set searchstring "*-OLD"

# Note the use of [list] to create a partial command application
# This is a standard Tcl technique; it's one of the things that [list] is designed to do
foreach dir [fileutil::find $rootdir [list myMatcher $searchstring]] {
    puts $dir
}