From: Robert Klemme Date: 2008-12-21T23:46:43+09:00 Subject: Re: get first and last line from txt file - how? On 20.12.2008 17:46, Thomas Preymesser wrote: > 2008/12/20 Yaser Sulaiman : >> I'm just wondering.. >> Let's say that we only need to read the last line. Can we do that without >> reading the other lines? > > Yes. Position your file pointer to the last byte in a file, read and > collect backwards each byte until you find a newline character (or the > first byte of the file). This is the last line. You have to admit that this approach is rather inefficient. Here's a more efficient variant - especially for large files: $ cat r.rb #!/bin/env ruby OFFSET = 512 # > 2 * assumed avg line length file = ARGV.shift or abort "ERROR: need a file name" File.open file do |io| first = io.gets break unless first puts first limit = io.stat.size offset = OFFSET lines = [] while lines.size < 2 && offset <= limit io.seek -offset, IO::SEEK_END lines = io.readlines offset += OFFSET end # while lines.size < 2 puts lines.last unless lines.empty? end Cheers robert