Reading the last n lines of a file in Ruby?

前端 未结 8 1101
北荒
北荒 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

    Improved version of manveru's excellent seek-based solution. This one returns exactly n lines.

    class File
    
      def tail(n)
        buffer = 1024
        idx = [size - buffer, 0].min
        chunks = []
        lines = 0
    
        begin
          seek(idx)
          chunk = read(buffer)
          lines += chunk.count("\n")
          chunks.unshift chunk
          idx -= buffer
        end while lines < ( n + 1 ) && pos != 0
    
        tail_of_file = chunks.join('')
        ary = tail_of_file.split(/\n/)
        lines_to_return = ary[ ary.size - n, ary.size - 1 ]
    
      end
    end
    

提交回复
热议问题