Ruby find string in file and print result

后端 未结 3 1509
傲寒
傲寒 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/
    

提交回复
热议问题