最主要的是使用seek这个命令,从文件的末尾开始读字符。读到一个换行符 \n 之后,计数器加一,直到找到符合要求的行数后,读内容到文件末尾输出。支持 –f 部分的想法是,在文件最后的位置不断地循环读,发现新内容后就进行输出。
脚本存在的问题:不支持多个文件,tail命令本身是可以支持的;不断循环的效率太低,应该有更好的办法可以优化。
1
#
!/usr/bin/ruby
2
3 line = ARGV[0]
4 filename = ARGV[1]
5
6 unless line && filename then
7 print " Invalid parameter.\n "
8 print " Usage:ruby tail.rb line filename\n "
9 end
10 line = line.to_i
11
12 begin
13 io = open(filename)
14 n = 0
15 lc = 0
16 stack = Array.new
17
18 while lc < line + 1 do
19 n = n + 1
20 io.seek( -n, IO::SEEK_END )
21 if io.pos == 0 then
22 break
23 end
24 # break unless io.seek( -n ,IO::SEEK_END)
25 s = io.read( 1 )
26 if /\n/ =~ s then
27 lc = lc + 1
28 end
29 end
30
31 io.seek(-n, IO::SEEK_END)
32 s = io.read()
33 last = io.pos
34 print s
35
36 while item = io.read() do
37 if ! item.empty? then
38 print item
39 last = io.pos
40 else
41 io.pos = last
42 end
43 end
44 rescue
45 print $@, " \n "
46 end
2
3 line = ARGV[0]
4 filename = ARGV[1]
5
6 unless line && filename then
7 print " Invalid parameter.\n "
8 print " Usage:ruby tail.rb line filename\n "
9 end
10 line = line.to_i
11
12 begin
13 io = open(filename)
14 n = 0
15 lc = 0
16 stack = Array.new
17
18 while lc < line + 1 do
19 n = n + 1
20 io.seek( -n, IO::SEEK_END )
21 if io.pos == 0 then
22 break
23 end
24 # break unless io.seek( -n ,IO::SEEK_END)
25 s = io.read( 1 )
26 if /\n/ =~ s then
27 lc = lc + 1
28 end
29 end
30
31 io.seek(-n, IO::SEEK_END)
32 s = io.read()
33 last = io.pos
34 print s
35
36 while item = io.read() do
37 if ! item.empty? then
38 print item
39 last = io.pos
40 else
41 io.pos = last
42 end
43 end
44 rescue
45 print $@, " \n "
46 end