I have 50 R scripts that I need to change the same line for all of them. Is there a way to do it all of them at the same time instead of one by one using "find" and "replace"?
            Asked
            
        
        
            Active
            
        
            Viewed 834 times
        
    4
            
            
        - 
                    1If you treat your documents like a text file, you can just open every file in the directory and use gsub...from a script you write to do so. – sconfluentus Jan 09 '18 at 22:49
- 
                    2Command line tools also work well for this - [this should get you started](https://unix.stackexchange.com/q/112023/219475) if you're not on Windows, [Powershell could probably work if you are on Windows](https://stackoverflow.com/q/2837785/903061). – Gregor Thomas Jan 09 '18 at 22:53
- 
                    Relevant post: https://stackoverflow.com/questions/11756353/replace-nth-line-in-a-text-file – zx8754 Jan 09 '18 at 23:22
- 
                    I also found this one for mac https://stackoverflow.com/questions/9704020/recursive-search-and-replace-in-text-files-on-mac-and-linux – MSS Jan 10 '18 at 01:01
1 Answers
7
            Loop through the files, read line by line (readLines gives a character vector), then update the Nth row, and output to new file:
lapply(list.files(path = ".", pattern = "*.R", full.names = TRUE),
       function(i){
         x <- readLines(i)
         # if we want for example change the 6th row:
         x[ 6 ] <- "# MY NEW LINES"
         # then write output
         write(x, file = paste0("myCleanOutput/folder/path/", basename(i)))
       })
But, if all R scripts are the same, maybe use Passing command line arguments to R CMD BATCH and have only 1 Rscript file which takes arguments.
 
    
    
        zx8754
        
- 52,746
- 12
- 114
- 209
- 
                    5+1 for the extra suggestion. there's often something wrong if you need to overwrite the same line in 50. Sounds like it should have been a function – OganM Jan 09 '18 at 23:30
