The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

Prepend Text To A File In Lua

TODO: Pull subtitle into page object
Code
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"
)

Notes

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

Prepend Text To A File In Lua

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


-- code
-- 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"
)


-- notes

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


-- blurb

Put text at the start a file with Lua


-- categories
-- Lua
-- Neovim

-- metadata
-- date: 2023-03-22 00:14:49
-- id: 2nm09cs0
-- site: aws
-- type: post
-- status: published