# How to read in only the last line of a file, in pure ruby, no external commands or libraries

**URL:** <https://www.ruby-forum.com/t/how-to-read-in-only-the-last-line-of-a-file-in-pure-ruby-no-external-commands-or-libraries/234552>\
**Category:** Ruby\
**Created:** [March 13, 2015, 10:15am UTC](https://www.ruby-forum.com/t/how-to-read-in-only-the-last-line-of-a-file-in-pure-ruby-no-external-commands-or-libraries/234552 "2015-03-13T10:15:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![addis\_a](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/c4cdca/32.png) [@addis\_a](https://www.ruby-forum.com/u/addis_a)\
**Post date:** [March 13, 2015, 10:15am UTC](https://www.ruby-forum.com/t/how-to-read-in-only-the-last-line-of-a-file-in-pure-ruby-no-external-commands-or-libraries/234552/1 "2015-03-13T10:15:31Z")

</div>

Hi,

My question is this:

How to read in only the last line of a file, in pure ruby, no external  
commands or libraries?

That means no full read-in of the whole file.

So no .readlines() call and similar.

I was told that I can use IO#seek to seek to the last  
position, then probably find the first occurance of \n  
there (seeking in the other direction; I am unsure how  
to do that actually, what if I read in through the  
first \n there?).

But how to do this in a simple fashion?

I’d then like to customize File, through a:

File.read\_last\_line\_of(‘foo.txt’)

Which would very quickly give me only the last line,  
delimiter being \n.

---

<div class="post-metadata">

**Author:** ![quik77](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/q/dec6dc/32.png) [@quik77](https://www.ruby-forum.com/u/quik77)\
**Post date:** [March 14, 2015, 8:27pm UTC](https://www.ruby-forum.com/t/how-to-read-in-only-the-last-line-of-a-file-in-pure-ruby-no-external-commands-or-libraries/234552/2 "2015-03-14T20:27:22Z")

</div>

f = File.open(‘data.txt’)  
f.seek(-2, IO::SEEK\_END) #pos -1 is newline at end of file  
last\_line = nil

while f.pos \> 0  
if f.getc == “\n”  
last\_line = f.read  
break  
else  
f.pos -= 2 #getc advances position by 1  
end  
end

if last\_line  
puts last\_line  
else  
puts f.read  
end

f.close

However, the simplest thing to do is:

last\_line = nil

IO.foreach(‘data.txt’) do |line|  
last\_line = line  
end

puts last\_line
