【问题标题】:Wildcard Search with tcl glob使用 tcl glob 进行通配符搜索
【发布时间】:2023-03-05 18:25:01
【问题描述】:

我正在尝试在子目录中搜索目录并返回任何与通配符 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

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

【问题讨论】:

    标签: tcl wildcard glob


    【解决方案1】:

    最明显的部分是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 中有实用命令:

    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
    }
    

    【讨论】:

    • 谢谢多纳尔。这是第二个 foreach 循环起到了作用 :) 一旦我添加了它,它就全部到位了。感谢您突出显示 fileutil 包,我将来可能需要使用它。
    猜你喜欢
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 2011-03-23
    • 2019-03-08
    • 1970-01-01
    • 2012-10-11
    • 2014-11-24
    • 1970-01-01
    相关资源
    最近更新 更多