[使用Ruby簡單實現的tail命令,支持動態輸出]

使用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 
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,947評論 18 139
  • 一、異同對比選擇1、Python和ruby的相同點: * 都強調語法簡單,都具有更一般的表達方式。python是縮...
    沃倫蓋茨閱讀 4,187評論 2 24
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,349評論 25 708
  • 不知道是出于怎樣一個機緣,或者是在哪看到的介紹推薦,《消失的地平線》這本書就在我的購物車中,正好碰到亞馬遜搞活動,...
    租了五顆星閱讀 329評論 0 0
  • 一:張弛有度,重視工作結束的時間和計劃什么時間工作同樣重要。合理安排時間,平衡工作與生活,讓時間更高效。 二:老...
    鄭公子vega閱讀 147評論 0 1