【问题标题】:Regex to find a file in Tcl正则表达式在 Tcl 中查找文件
【发布时间】:2011-05-10 08:12:25
【问题描述】:

我以前从未使用过 Tcl,但是,我需要为项目修改某个文件。我在 Perl 中使用过正则表达式,但是我不确定 Tcl 的语法。

我想要做的是允许用户执行脚本并输入必须搜索的文件名。我想在找到文件后搜索该文件并执行某些操作。到目前为止,这是我的一些伪代码。

set file_name [lindex $argv 0]

while(true) {
if { found file } {
 puts "Found file!"
 {
 else { file not found )
 puts "File not found!"

}

我不确定如何检查文件是否被找到?我通过输入从用户那里获得完整的文件名...

【问题讨论】:

  • “一旦找到”是什么意思?你想循环直到文件突然出现吗?是否需要遍历子目录直到匹配?
  • 卡洛斯,抱歉信息不足。我的意思是一旦在根目录中找到它。
  • 我从stackoverflow.com/q/4187684/301832 知道您正在从远程某处获取文件列表,因此涉及本地文件系统的解决方案不是这里的最佳推荐。 但你应该在你的问题中这么说!

标签: regex tcl


【解决方案1】:

如果您真的想使用正则表达式而不是 glob 模式,请定期获取文件列表(使用 glob)并搜索它。有用的是,lsearch 接受正则表达式语法:

# get the regexp:
set file_pattern [lindex $argv 0]

# scan current directory:
while 1 {
    set files [glob -nocomplain *]
    if {[lsearch -regexp $files $file_pattern] < 0} {
        puts "file not found"
    } else {
        puts "file found"
    }
    after 1000 ;# sleep for 1 second
}

请注意,在 tcl regexp 中没有特殊语法。它只是一个字符串。

【讨论】:

    【解决方案2】:

    您是否希望用户输入特定的文件名或带有 shell 样式通配符的内容?如果是后者,您需要使用glob 命令。

    其他人可能会提供更好的目录轮询技术,但也许:

    # a utility procedure for outputting messages
    proc log {msg} {puts "[clock format [clock seconds] -format %T] - $msg"}
    
    set file_pattern [lindex $argv 0]
    log "looking for $file_pattern"
    while {[llength [glob -nocomplain $file_pattern]] == 0} {
        after 30000 ;# sleep for 30 seconds
        log "still waiting"
    }
    log "found: [join [glob $file_pattern] ,]"
    

    【讨论】:

      猜你喜欢
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多