Ruby find string in file and print result
File.open 'file.txt' do |file| file.find { |line| line =~ /regexp/ }end
That will return the first line that matches the regular expression. If you want all matching lines, change find
to find_all
.
It's also more efficient. It iterates over the lines one at a time, without loading the entire file into memory.
Also, the grep
method can be used:
File.foreach('file.txt').grep /regexp/
The simplest way to get the root is to do:
rake routes | grep root
If you want to do it in Ruby, I would go with:
File.open("config/routes.rb") do |f| f.each_line do |line| if line =~ /root/ puts "Found root: #{line}" end endend
Inside text
you have the whole file as a string, you can either match against it using a .match
with regexp or as Dave Newton suggested you can just iterate over each line and check.Something such as:
f.each_line { |line| if line =~ /string/ then puts line end}