使用字符串匹配来搜索文件

时间:2015-08-13 08:35:37

标签: tcl

想要使用tcl在文件中搜索以找到匹配项。

这就是我所拥有的。

set search "random string"
set file [open "file.txt" r]
 while {![eof $file]} {
    gets $file data
    if {[ string match [string toupper $search] [string toupper $data] ] } {
    //works
    } else {
    //doesnt work
    }
 }

FILE.TXT

chicken.dinner:1439143130
random.strings:1439143130
more random strings:1439413390
random.strings.that.contain-special.characters:1439441566

无法匹配"随机字符串"与文件中的内容有关。感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

如果您只想使用string match,请在此处使用glob模式*

set search "random string"
set file [open "file.txt" r]
 while {[gets $file data] != -1} {
    if {[string match *[string toupper $search]* [string toupper $data]] } {
        puts "Found '$search' in the line '$data'"
    } else {
        # does not match case here 
    }
 }

输出

Found 'random string' in the line 'more random strings:1439413390'

由于我们想知道该行是否包含搜索字符串,因此我们在开头和结尾添加了*。它可以匹配任意数量的序列。

参考: mosquitto-auth-plug

相关问题