Return to Snippet

Revision: 52947
at November 7, 2011 05:47 by scruffpuff


Initial Code
Simplest
fgrep 'mystring' filename.txt

Now it depends on whether to just verify the string is there:

def check_file( file, string )
File.open( file ) do |io|
io.each {|line| line.chomp! ; return true if line.include? string}
end

false
end

or whether to get the first matching line:

def check_file( file, string )
File.open( file ) do |io|
io.each {|line| line.chomp! ; return line if line.include? string}
end

nil
end

or whether to get all matching lines:

def check_file( file, string )
lines=[]

File.open( file ) do |io|
io.each {|line| line.chomp! ; lines << line if line.include? string}
end

lines
end

or whether the condition is a regexp:

def check_file( file, rx )
File.open( file ) do |io|
io.each {|line| line.chomp! ; return true if rx =~ line}
end

false
end

Initial URL


Initial Description


Initial Title
Finding strings in Files in Ruby

Initial Tags
file

Initial Language
Ruby