代码之家  ›  专栏  ›  技术社区  ›  Gerhard

使用ruby在路径中的文件中搜索文本

  •  1
  • Gerhard  · 技术社区  · 15 年前

    我需要搜索所有 *.c 在路径中查找对 *.h 查找未使用的C头。我写了一个Ruby脚本,但感觉很笨拙。

    我创建了一个包含所有C文件的数组和一个包含所有H文件的数组。 我迭代头文件数组。对于每个头,我打开每个C文件并查找对头的引用。

    有更简单或更好的方法吗?

    require 'ftools'
    require 'find'
    
    # add a file search
    class File
      def self.find(dir, filename="*.*", subdirs=true)
        Dir[ subdirs ? File.join(dir.split(/\\/), "**", filename) : File.join(dir.split(/\\/), filename) ]
      end
    end
    
    files = File.find(".", "*.c", true)
    headers = File.find(".", "*.h", true)
    
    headers.each do |file|
    
      #puts "Searching for #{file}(#{File.basename(file)})"
      found = 0
    
      files.each do |cfile|
        #puts "searching in #{cfile}"
        if File.read(cfile).downcase.include?(File.basename(file).downcase)
            found += 1
        end
      end
    
      puts "#{file} used #{found} times"
    
    end
    
    4 回复  |  直到 15 年前
        1
  •  3
  •   Mike Woodhouse    15 年前

    正如已经指出的,您可以使用 Dir#glob 以简化文件查找。您还可以考虑切换循环,这意味着打开每个C文件一次,而不是每个H文件一次。

    我会考虑使用类似下面的代码,它在3秒内运行在Ruby源代码上:

    # collect the File.basename for all h files in tree
    hfile_names = Dir.glob("**/*.h").collect{|hfile| File.basename(hfile) }
    
    h_counts = Hash.new(0) # somewhere to store the counts
    
    Dir.glob("**/*.c").each do |cfile| # enumerate the C files
      file_text = File.read(cfile) # downcase here if necessary
      hfile_names.each do |hfile|
        h_counts[hfile] += 1 if file_text.include?(hfile)
      end
    end
    
    h_counts.each { |file, found| puts "#{file} used #{found} times" }
    

    编辑:不会列出任何C文件中未引用的H文件。要确保捕获这些内容,必须显式初始化哈希:

    h_counts = {}
    hfile_names.each { |hfile| h_counts[hfile] = 0 }
    
        2
  •  1
  •   YOU    15 年前

    搜索 *.c *.h 文件,您可以使用 Dir.glob

    irb(main):012:0> Dir.glob("*.[ch]")
    => ["test.c", "test.h"]
    

    要搜索任何子目录,可以通过 **/*

    irb(main):013:0> Dir.glob("**/*.[ch]")
    => ["src/Python-2.6.2/Demo/embed/demo.c", "src/Python-2.6.2/Demo/embed/importexc.c",
    .........
    
        3
  •  0
  •   Trevoke    15 年前

    好吧,一旦找到.c文件,就可以对它们执行以下操作:

    1)打开文件并将文本存储在变量中 2)使用‘grep’: http://ruby-doc.org/core/classes/Enumerable.html#M003121

        4
  •  0
  •   Sam    15 年前

    Rake API中的文件列表对此非常有用。只需注意列表的大小比您有内存处理的要大。:)

    http://rake.rubyforge.org/