Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit specific line in a file with lua

Tags:

lua

I'm trying to edit a specific line in a file using lua. For example, I have a file with 12 lines. I want to edit the 2nd line ONLY. Line 1: Hello Line 2: Hello again The output file would be for example Line 1: Hello Line 2: Whatever but without caring what's the content of the 2nd line. Just by the number of the line.

like image 451
BananaMaster Avatar asked Nov 17 '25 16:11

BananaMaster


1 Answers

I figured it out after all. Here's the code:

function Initialize()

    inputFile = 'PathToFile'

end
function Edit()

    local file = io.open(inputFile, 'r')
    local fileContent = {}
    for line in file:lines() do
        table.insert (fileContent, line)
    end
    io.close(file)

    fileContent[3] = 'This line has been edited'

    file = io.open(inputFile, 'w')
    for index, value in ipairs(fileContent) do
        file:write(value..'\n')
    end
    io.close(file)
end
like image 95
BananaMaster Avatar answered Nov 19 '25 09:11

BananaMaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!