Saturday, June 13, 2009

Searching String(s) in file(s) using Ruby

Searching String(s) in file(s) using Ruby is very simiple. Here is the sample code to manipulate it.

# searching a string in a file
def print_line_containing(file, str)
File.open(file).grep(/#{str}/).each do |line| puts "#{line}" end
end

# searching multiple strings in a file
def print_line_containing(file, str1, str2)
File.open(file).grep(/#{str1}\s+#{str2}/).each do |line| puts "#{line}" end
end


# searching multiple strings in multiple files
def print_line_containing(file_array, str)
file_array.each do |file|
File.open(file).grep(/#{str1}\s+#{str2}/).each do |line| puts "#{line}" end
end
end

I hope this will help you all!

No comments: