Reading the last n lines of a file in Ruby?

前端 未结 8 1097
北荒
北荒 2020-11-30 09:59

I need to read the last 25 lines from a file (for displaying the most recent log entries). Is there anyway in Ruby to start at the end of a file and read it backwards?

相关标签:
8条回答
  • 2020-11-30 10:22

    How about:

    file = []
    File.open("file.txt").each_line do |line|
      file << line
    end
    
    file.reverse.each_with_index do |line, index|
      puts line if index < 25
    end
    

    The performance would be awful over a big file as it iterates twice, the better approach would be the already mentioned read the file and store the last 25 lines in memory and display those. But this was just an alternative thought.

    0 讨论(0)
  • 2020-11-30 10:26

    Is the file large enough that you need to avoid reading the whole thing? If not, you could just do

    IO.readlines("file.log")[-25..-1]
    

    If it is to big, you may need to use IO#seek to read from near the end of the file, and continue seeking toward the beginning until you've seen 25 lines.

    0 讨论(0)
提交回复
热议问题