Replace contents of a file and save file in directory - R

I'm trying to change contents of a file based on a pattern and save the file in the same directory. Below is my code,

designFile <- "/proj/desk/design.scs"
designFile <- readLines(designFile)
pattern <- "esd_event"     
rownos <- grep(pattern, designfile)
rownotoreplace <- rownos[length(rownos)]
print(designfile[rownotoreplace])
designFile[rownotoreplace] <- paste("+ esd_event=", input$esd_event, sep="")
filename = designfile         
fConn <- file(filename,open="w")
for(i in 1:length(designFile)){
  writeLines(designFile[i], con = fConn, sep = "") 
}
close(fConn)

The file in which the string change looks like,

+ cor_zgdiode   = sigma
+ corner_sigma  = 3
+ corner_sigma_sg = corner_sigma
+ corner_sigma_eg = corner_sigma
+ corner_sigma_sram = corner_sigma
+ corner_sigma_ldmos = corner_sigma
+ corner_sigma_wire = corner_sigma
+ cor_noin      = 0
+ cor_noip      = 0
+ cor_tnoin     = 0
+ cor_tnoip     = 0
+ fnoi_cor_sgn_sw    = cor_noin
+ fnoi_cor_egn_sw    = cor_noin
+ fnoi_mc_sgn_sw    = 1
+ fnoi_mc_egn_sw    = 1
+ fnoi_cor_sgp_sw    = cor_noip
+ fnoi_cor_egp_sw    = cor_noip
+ fnoi_mc_sgp_sw    = 1
+ fnoi_mc_egp_sw    = 1
* ESD Global switches ********
+ esd_event=0
+ esd_exit=1
+ esd_extr=0

The contents of the file is dynamic and the number of lines might vary based on user input. I'm able to replace the string, "esd_event" with my code that I attached, but I'm not able to save the file in the same directory after replacing the string.

I would like to know how to save

There may be some confusion with the names, designFile and designfile are 2 separate variables since R is case-sensitive.

designFile <- "/proj/desk/design.scs"

Here designFile contains the path to the file.

designFile <- readLines(designFile)

Now you rewrite the variable designFile with the contents of the file. The path is not saved anywhere anymore.

filename = designfile
fConn <- file(filename,open="w")

if designFile and designfile are the same, then it means you're trying to create a file called "+ cor_zgdiode = sigma", then a second file called "+ corner_sigma = 3" etc... File names with spaces, "+" and "=" should probably be avoided, and depending on the operating system, will not work at all.

If you just want to save your modified file, you don't need a loop at all, you can simply do:

file_path <- "/my/path.scs"
new_path <- "/my/path_modif.scs"
file_content <- readLines(file_path)
modified_content <- do_things(file_content)
writeLines(modified_content, new_path)

(also, are you sure about your sep="", that will make a result file with a single big line, doesn't sound like a good idea in general).

Thanks @AlexisW It worked.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.