#!/usr/bin/ruby
line = ARGV[0]
filename = ARGV[1]
unless line && filename then
print "Invalid parameter.\n"
print "Usage:ruby tail.rb line filename\n"
end
line = line.to_i
begin
io = open(filename)
n = 0
lc = 0
stack = Array.new
while lc < line + 1 do
n = n + 1
io.seek( -n, IO::SEEK_END )
if io.pos == 0 then
break
end
#break unless io.seek( -n ,IO::SEEK_END)
s = io.read( 1 )
if /\n/ =~ s then
lc = lc + 1
end
end
io.seek(-n, IO::SEEK_END)
s = io.read()
last = io.pos
print s
while item = io.read() do
if ! item.empty? then
print item
last = io.pos
else
io.pos = last
end
end
rescue
print $@, "\n"
end
测试
ruby tail.rb 10 /var/log/td-agent/td-agent.log