TCL - 在文件中查找常规模式并返回出现次数和出现次数

pra*_*thi 4 tcl

我正在编写一个代码来regular expression从文件中grep一个模式,并输出该正则表达式及其发生的次数.

这是代码:我试图在我的文件hello.txt中找到模式"grep":

set file1 [open "hello.txt" r]
set file2 [read $file1]
regexp {grep} $file2 matched
puts $matched
while {[eof $file2] != 1} {
set number 0
if {[regexp {grep} $file2 matched] >= 0} {
 incr number
}

puts $number
}
Run Code Online (Sandbox Code Playgroud)

我得到的输出:

grep

--------
can not find channel named "qwerty
iiiiiii
wxseddtt
lsakdfhaiowehf'
jbsdcfiweg
kajsbndimm s
grep
afnQWFH
 ACV;SKDJNCV;
    qw  qde 
 kI UQWG
grep
grep"
    while executing
"eof $file2"
Run Code Online (Sandbox Code Playgroud)

gle*_*man 6

eof在while循环中检查通常是一个错误- 检查返回代码gets:

set filename "hello.txt"
set pattern {grep}
set count 0

set fid [open $filename r]
while {[gets $fid line] != -1} {
    incr count [regexp -all -- $pattern $line]
}
close $fid

puts "$count occurrances of $pattern in $filename"
Run Code Online (Sandbox Code Playgroud)

另一个想法:如果你只计算模式匹配,假设你的文件不是太大:

set fid [open $filename r]
set count [regexp -all -- $pattern [read $fid [file size $filename]]]
close $fid
Run Code Online (Sandbox Code Playgroud)