lua读取linux文件内容,使用lua模拟tail -n命令读取最后n行
文章目錄
[隱藏]
實現思路
lua代碼
用法
最近需要使用lua讀取文件的最后n行數據,但不想調用linux中的tail命令來獲取,于是使用純lua來實現。
實現思路
把文件指針偏移距離文件尾x個字節
讀取x個字節數據
在這x個字節數據中查找換行符n,如果找到n個換行符,把文件指針偏移到第n個換行符的位置,輸出全部內容
如果找不到足夠的換行符,繼續把文件指針在當前位置向文件頭方向偏移x個字節
返回2步驟循環,直到找到足夠換行符或到文件頭
lua代碼
tail.lua
#!/usr/bin/lua if arg[1] == "-n" then tail_lines = arg[2] filepath = arg[3] else tail_lines = 10 filepath = arg[1] end -- 一次讀取512字節數據 read_byte_once = 512 offset = 0 fp = io.open(filepath,"r") if fp == nil then print("open file "..filepath.." failed.") os.exit(0) end line_num = 0 while true do -- 每次偏移read_byte_once字節 offset = offset - read_byte_once -- 以文件尾為基準偏移offset if fp:seek("end",offset) == nil then -- 偏移超出文件頭后將出錯,這時如果是第一次讀取的話,直接將文件指針偏移到頭部,否則跳出循環輸出所有內容 if offset + read_byte_once == 0 then fp:seek("set") else break end end data = fp:read(read_byte_once) -- 倒轉數據,方便使用find方法來從尾讀取換行符 data = data:reverse() index = 1 while true do -- 查找換行符 start = data:find("n",index, true) if start == nil then break end -- 找到換行符累加 line_num = line_num + 1 -- 找到足夠換行符 if tail_lines + 1 == line_num then -- 偏移文件符指針到第line_num個換行符處 fp:seek("end",offset+read_byte_once-start+1) io.write(fp:read("*all")) fp:close() os.exit(0) end index = start + 1 end end -- 找不到足夠的行,就輸出全部 fp:seek("set") io.write(fp:read("*all")) fp:close()
用法
讀取centos.log最后10行
./tail.lua centos.log
讀取centos.log最后20行
./tail.lua -n 20 centos.log
使用lua模擬tail -n命令讀取最后n行
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的lua读取linux文件内容,使用lua模拟tail -n命令读取最后n行的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux网络协议栈之数据包处理过程,L
- 下一篇: linux读取环境变量替换,linux