Question

What's the best way to search for a string in a file?

The title speaks for itself really. I only want to know if it exists, not where it is. Is there a one liner to achieve this?

 45  54010  45
1 Jan 1970

Solution

 52
File.open(filename).grep(/string/)

This loads the whole file into memory (slurps the file). You should avoid file slurping when dealing with large files. That means loading one line at a time, instead of the whole file.

File.foreach(filename).grep(/string/)

It's good practice to clean up after yourself rather than letting the garbage collector handle it at some point. This is more important if your program is long-lived and not just some quick script. Using a code block ensures that the File object is closed when the block terminates.

File.foreach(filename) do |file|
  file.grep(/string/)
end
2009-03-12

Solution

 10

grep for foo OR bar OR baz, stolen from ruby1line.txt.

$  ruby -pe 'next unless $_ =~ /(foo|bar|baz)/' < file.txt
2009-03-11