Regex to find a file in Tcl
I've never used Tcl previously, however, I need to modify a certain file for a project. I have used regex with Perl, however I'm unsure of the syntax with Tcl.
What I want to do is allow the user to execute the script and type in a file name that has to be searched. I want to search for the file once its found and do something. So far, here's my somewhat pseudo-code.
set file_name [lindex $argv 0]
while(true) {
if { found file } {
puts "Found file!"
{
else { file n开发者_运维知识库ot found )
puts "File not found!"
}
I'm not sure how to check if the file was found or not? I get the complete filename from the user via an input ...
If you really want to use a regular expression instead of glob patterns then periodically get a list of files (using glob
) and search through it. Helpfully, lsearch accepts regexp syntax:
# 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
}
Note that in tcl regexp does not have a special syntax. It is simply a string.
Are you expecting the user to enter a specific filename or something with shell-style wildcards? If the latter, you'll want to use the glob
command.
Others may offer better directory polling techniques, but perhaps:
# 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] ,]"
精彩评论