我试图在子目录中搜索目录,并返回任何符合通配符 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
始终 返回一个名字的列表。因此,你需要像这样做最里面的循环。
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 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
}