Search code examples
fileluaio

How to Read only the last line of a text file in Lua?


I have a program that generates text fiels that can be up to 20 mets in size. Sometimes I only care about the last line in the file, is there a way to read just that line with out wasting memory reading the rest of the file?


Solution

  • I could be mistaken but without resorting to some trickery, it seems that you can't. However, if you have a rough estimate of the length of the lines, you can open a file and then seek from the end, say, 1Kb.

    local f = io.open([[c:\test_file.txt]], "r")
    local len = f:seek("end")
    
    f:seek("set", len - 1024)
    local text = f:read("*a")
    
    print(string.match(text, "[^%c]*$"))
    f:close()
    

    Hope this helps. Take into account that the pattern needs some refinement. It currently assumes that no control characters appear on a line. If your line has i.e. tabs, then it will capture from there till the end of file.