apl9ig
Last Updated: January 28, 2019
·
1.156K
· rafaelbarbosa

Little ruby snippet to find words in files recursively

``` ruby

words = ['word1','word2']

for file in Dir['**/*'].reject {|fn| File.directory?(fn) || fn == 'find.rb' } do
    File.open(file).each_line.with_index do |line, i|
        words.any? { |word| if(line.include?(word)) then puts(file + ':' + i.to_s ) end }
    end
end

```

2 Responses
Add your response

5721

Rebound:

module WordSearch
  def self.files_for(path, *words)
    files(path).each do |file, lines|
      File.open(file, 'r').each_line.with_index do |line, i|
        words.each do |word|
          puts "#{file}:#{i}:#{word}" if line.include?(word)
        end
      end
    end
  end

  def self.files(search_path='')
    search_path << "**/*.*"
    Dir[search_path].reject { |f| f == __FILE__ }
  end
end

WordSearch.files_for('/Desktop/', 'word1', "word2")
over 1 year ago ·
5722

Very clean, cool :)

over 1 year ago ·