正则表达式在Tcl中查找文件

时间:2010-11-15 16:20:18

标签: regex tcl

我之前从未使用过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!"

}

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

2 个答案:

答案 0 :(得分:4)

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

# 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没有特殊的语法。它只是一个字符串。

答案 1 :(得分:3)

您是否希望用户输入特定文件名或带有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] ,]"