Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Prepend Text To A File In Lua

This is what I'm using to prepend text to a file from a Neovim Telescope extension.

lua
prepend_file = function(file_path, line)
	local tmp_path = file_path .. ".tmp"
	local file = io.open(file_path, 'r') 
	local tmp = io.open(tmp_path, 'a')
	tmp:write(line .. "\n")
	for line in file:lines() do
		tmp:write(line)
		tmp:write("\n")
	end
	file:close()
	tmp:close()
	os.remove(file_path)
	os.rename(tmp_path, file_path)
end

prepend_file(
	"path/to/file.txt",
	"this is a new line"
)

- This doesn't have any error checking in it. Could definitely use that.

Put text at the start a file with Lua