Ruby find string in file and print result

后端 未结 3 1506
傲寒
傲寒 2020-12-18 23:23

It\'s been a very long time since I\'ve used ruby for things like this but, I forget how to open a file, look for a string, and print what ruby finds. Here is what I have:

相关标签:
3条回答
  • 2020-12-19 00:01
    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/
    
    0 讨论(0)
  • 2020-12-19 00:05

    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
      end
    end
    
    0 讨论(0)
  • 2020-12-19 00:16

    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
    }
    
    0 讨论(0)
提交回复
热议问题