5

Let's say I have a .txt file that contains a string. How can I delete some characters, or insert others between them? Example: .txt file contains "HelloWorld" and I want to insert a comma after "Hello" and a space after that. I only know how to write from start and append a file

local file = io.open("example.txt", "w")
file:write("Example")
file.close()

1 Answers1

5

You need to break this down into distinct steps.

The following example replaces "HelloWorld" with "Hello, World"

 --
 --  Read the file
 --
 local f = io.open("example.txt", "r")
 local content = f:read("*all")
 f:close()

 --
 -- Edit the string
 --
 content = string.gsub(content, "Hello", "Hello, ")

 --
 -- Write it out
 --
 local f = io.open("example.txt", "w")
 f:write(content)
 f:close()

Of course you need to add error-testing, etc.

  • 3
    If you know you don't want to make the file any smaller than it currently is, you can also use `'r+'` mode when opening the file and instead of closing and reopening it, just use `f:seek('set')` after `f:read('*a')` to move back to the beginning of the file and overwrite the contents. This has the advantage that the file remains open the whole time, and prevents a race condition with other processes modifying the file between when you read it and wrote the updated file. – bcrist Apr 09 '17 at 20:40