[使用Ruby简单实现的tail命令,支持动态输出]

2016-12-27  本文已影响0人  风恋绝尘

使用Ruby简单实现的tail命令,支持动态输出

#!/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 
上一篇 下一篇

猜你喜欢

热点阅读