Last active
October 16, 2022 05:42
-
-
Save mattjbayly/9c56ec80ae291ff00589ffa3440806a1 to your computer and use it in GitHub Desktop.
Replace multiple strings across multiple text files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' Replace multiple strings across multiple files with original values and replacement values. | |
#' | |
#' files - A character string of file names to work through. | |
#' f - A character string of original values that you want to replace. | |
#' r - A character string of replacement values (f->r). | |
multi_replace <- function(files="", f="", r=""){ | |
file_line = data.frame() # (optional) tracking table | |
#loop through each file separately | |
for(j in 1:length(files)){ | |
nl <- suppressWarnings(readLines(files[j])) # read file line by line | |
# loop through each of the find and replace values within each file | |
for(i in 1:length(f)){ | |
cnt_replaced <- data.frame(filename = files[j], find = f[i], replace = r[i], times = length(grep(f[i], nl))) # fill tracking table with values | |
file_line <- rbind(file_line, cnt_replaced) # populate tracking table count of find & replace within each file | |
nl <- gsub(f[i], r[i], nl) # find and replace value line by line | |
} | |
write(nl, file = files[j]) # save files with same name & overwrite old | |
rm(nl) # don't overwrite with previous file if error. | |
} | |
return(file_line) # print the tracking table | |
} | |
### EXAMPLE ### | |
# local directory with files you want to work with | |
setwd("C:/Users/DW/Desktop/New folder") | |
# get a list of files based on a pattern of interest e.g. .html, .txt, .php | |
filer = list.files(pattern=".php") | |
# f - list of original string values you want to change | |
f <- c("localhost","olddatabase","root","oldpassword") | |
# r - list of values to replace the above values with | |
# make sure the indexing of f & r | |
r <- c("newhost", "newdb", "newroot", "newpassword") | |
# Run the function and watch all your changes take place ;) | |
tracking_sheet <- multi_replace(filer, f, r) | |
tracking_sheet |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment