Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TCL-在文件中查找规则模式,并返回出现次数和出现次数_Tcl - Fatal编程技术网

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

TCL-在文件中查找规则模式,并返回出现次数和出现次数,tcl,Tcl,我正在编写一个代码,从文件中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 matc

我正在编写一个代码,从文件中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
}
我得到的输出:

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"

该错误消息是由命令“
eof$file2”
引起的。原因是
$file2
不是文件句柄(响应通道),而是包含文件
hello.txt
本身的内容。您可以使用
set file2[read$file1]
读取此文件内容

如果您想这样做,我建议您将
$file2
重命名为
$filecontent
之类的名称,并在包含的每一行上循环:

foreach line [split $filecontent "\n"] {
  ... do something ...
}

在while循环中检查
eof
通常是错误的——请检查
get
中的返回代码:

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"
另一个想法是:如果您只是计算模式匹配,假设您的文件不是太大:

set fid [open $filename r]
set count [regexp -all -- $pattern [read $fid [file size $filename]]]
close $fid

格伦很合适。下面是另一个解决方案:Tcl附带fileutil包,其中包含grep命令:

package require fileutil
set pattern {grep}
set filename hello.txt
puts "[llength [fileutil::grep $pattern $filename]] occurrences found"

如果您关心性能,请使用Glenn的解决方案。

+1,但我认为您的意思是TclLib或ActiveTcl附带fileutil——它不是核心package@Glenn:我的错误,是的fileutil是tcllib的一部分。