On 24.08.2007 16:19, Rebhan, Gilbert wrote:
> i want to count the occurence of a searchstring in all files
> below a directory and all its subdirectories
> 
> i have =
> 
> matches=0
> Dir.glob("E:/test/foobar/scripts/**/**.xml").each do |f|
>   matches += File.new(f).read.scan('<if>').size
>   puts f
> end
> 
> puts "Matchcount == " + matches.to_s
> puts "Scanned Files == " +
> Dir.glob("E:/test/foobar/scripts/**/**.xml").size.to_s
> 
> Is there a better way ?

Yes, you should at least avoid globbing twice.  This is really slow. 
Also, you do not need two stars for the file name.

Then, you do not close files properly when reading.  A simplified 
version looks like this

files = Dir["E:/test/foobar/scripts/**/*.xml"]
matches = files.inject(0) {|sum,f| sum + File.read(f).scan('<if>').size}
printf "%10d matches\n%10d files\n", matches, files.size

If you have a lot of files it may pay off to use Find.find instead of Dir[].

Kind regards

	robert