This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
CRUGG's profile picture

Program that copies a file and replaces specific parts of text.

Started by CRUGG, 02 May 2018 - 02:52 PM
CRUGG #1
Posted 02 May 2018 - 04:52 PM
Hello!

I want to make a program, which you execute like textreplacer originalfile.rf replacedfile.
replaced file doesn't exists, only originalfile. Original file contains something like:
This is a text to be replaced.

The program now copies the file to the second argument (replacedfile), but also replaces all text elements I (as the developer of the program) specified to be replaced. So the end product should look like this:
This is a text which was replaced.

So, I specified that to be will be replaced with which was.

My questions are:
- How can I make the text be replaced in the copy?
- How can I make the first file (the file to be copied) need to have a specific ending (like .rf), so the file must be *.rf. (Not the second file/argument)

If you don't understand what I mean:
The things above are just examples; I want to make something like my own programing language where files have to have a specific file extension. You can run the program now and it compiles it to runable lua. The output file doesn't have to have a specific extension.
KingofGamesYami #2
Posted 02 May 2018 - 06:41 PM
- String.gsub
-
string.reverse( fileName ):sub(1,3) == "fr."

Edit: fixed extension (thanks BB!)
Edited on 10 May 2018 - 08:50 PM
CRUGG #3
Posted 10 May 2018 - 08:26 AM
- String.gsub
-
string.reverse( fileName ):sub(1,3) == ".rf"

I don't really understand those.
Bomb Bloke #4
Posted 10 May 2018 - 08:45 AM
It's supposed to be a conditional statement that checks whether the last three characters of your "fileName" string match ".rf". It won't work, though - it first reverses the character order and then compares the first three characters of the result, meaning it should then be checking against "fr."…

A more resilient check would be:

if fileName:lower():sub(#filename - 2) == ".rf" then  --# If a lower case version of the file name's last three characters equals ".rf" then...
  print("File has an rf extension.")
end

See here for some details on "lower" and "sub", as well as the other functions you can use on strings of text. gsub in particular will be useful for your text-replacing needs!
Windows10User #5
Posted 10 May 2018 - 08:21 PM

local tArgs = {...}

if #tArgs < 2 then
   error("filereplacer <original file> <destination file>", 0)
end

local origPath = tArgs[1]
local replPath = tArgs[2]

local origFile = fs.open(origPath, "r")
local replFile = fs.open(replPath, "w")

while true do
   local line = origFile.readLine()
   if line == nil then break
   else
      replFile.writeLine(string.gsub(line, "to be", "was")
end

replFile.close()
print("Success!")

If you don't understand something, ask.

- String.gsub
-
string.reverse( fileName ):sub(1,3) == ".rf"

Fix:
string.reverse( fileName ):sub(1,3) == "fr."