Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a file and search for a word?

How can I open a file and search for a word inside it using Ruby?

like image 764
Markus Avatar asked Dec 13 '09 13:12

Markus


People also ask

How do I search for a specific Word in a file?

To open the Find pane from the Edit View, press Ctrl+F, or click Home > Find. Find text by typing it in the Search the document for… box.

How do I search for a Word with an open?

Right-click file and select program Right-click the file you want to open. In the pop-up menu, select the Open with option. If available, choose the Microsoft Word program option in the Open with menu.

How do I search for a Word without opening it?

Click in the search box in the upper right corner, below the ribbon. Enter the word you want to search for, then press Enter. Was this reply helpful?


2 Answers

All presented solution have a time complexity of O(n). For simplicity I use String#include? to check for the word. This could be done instead with a regular expression in the form string=~ regex.

Read the complete file and search in it.

File.read(filename).include?(word)

If your file is very large, this is not an optimal solution, as you would read the complete file into memory and start searching afterwards. Your memory complexity is O(n)

Read the file line by line and search in each line

File.open(filename) do |f|
  f.any? do |line|
    line.include?(word)
  end
end

If your file is very large, but you know your lines are upperbounded by a constant value, you now have a memory complexity of O(1).

Read chunks of the file and search in it

File.open(filename) do |f|
  tmp= f.read(1024)
  next true if tmp.include?(word)
  until f.eof?
    tmp= tmp[(-1*word.size)..-1] + f.read(1024)
    next true if tmp.include?(word)
  end
  next false
end

In this variant, we are reading equaly sized chunks from the file. So no matter what the conditions of the file are, our memory complexity is O(1)

like image 136
johannes Avatar answered Sep 20 '22 08:09

johannes


Something like this might help:

def word_exists_in_file
   f = File.open("your_file.txt") #opens the file for reading
   f.each do line
      print line
      if line.match /your_word_to_match/
         return true
      end
   end
   false
end
like image 38
Ben Scheirman Avatar answered Sep 20 '22 08:09

Ben Scheirman