Search code examples
rfile-ioediting

Reading In Source Code From .R File, Editing It, Then Saving It


I'm looking to see if there is a way in R to read in a .R file's source code as text. What I'd like to do is give the path to a .R file, have R grab that R file and return the source code, in text, of that R file.

After that, I plan to make a gsub edit on the source code, and then saving the edited text to the same location (which I believe I can do with the save function). The gsub regular expression is solid (as I wrote the code) and know that will only match what I want it to match and replace.

Naturally, I'm backing up everything before attempting any of this. The part that I am having the most issue with is reading in a .R file's code as text to be edited. I'm also not sure if this would destroy the formatting of the R file, but obviously it would be preferred to not do that. Any help is greatly appreciated!


Solution

  • code <- readLines("<path>")
    code_edited <- gsub("foo", "bar", code)
    writeLines(code_edited, "<path>")