用R替换多个文件中的多个字符串

Replace multiple strings in multiple files with R

我在一个文件夹中有大约 700,000 个文件,我需要在其中查找多个字符串并将其替换为不同的其他字符串(所有 4 个字符代码)。不确定文件中是否存在字符串。我正在尝试使用 gsub 但我找不到如何使用正则表达式来完成它。谁能告诉我一个好的有效方法来处理这个任务?

这是我目前使用的代码。它仅适用于一条 y <- gsub(...) 指令,但不适用于我的目的,显然是因为在定义 y 变量时只考虑了最后一条 gsub 指令...

chm_files <- list.files(getwd(), pattern=("^[[:digit:]]*.chm$"), full.names=F)

for(chm_file in chm_files) {
  x <- readLines(chm_file)
  y <- gsub("AG02|AG07|AG05|AG18|AG19|AG08|AG09|AG17", "AGRL", x)
  y <- gsub("SB28|SB42|SB43|SB33|SB41|SB34|SB39|SB35", "SWHT", x)
  y <- gsub("WB28|WB42|WB43|WB32|WB09|WB33|WB41|WB26", "BARL", x)
  y <- gsub("WW02|WW25|WW08|WW31|WW05|WW28|WW19|WW42", "WWHT", x)
  cat(y, file=chm_file, sep="\n")
}

我确信在各种 R 包中已经有许多针对此任务的预构建函数,但无论如何我只是为自己和其他人编写了这个 use/modify。除了上面的任务请求之外,它还打印出跨文件功能所做的所有更改计数的跟踪日志:multi_replace.

这里有一些示例代码应该如何 运行

# 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","dbtest","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
setwd("D:/R Training Material Kathmandu/File renaming procedures")
filer = list.files(pattern="2016")
f <- c("DATA,","$")
r <- c("","")
tracking_sheet <- multi_replace(filer, f, r)
tracking_sheet

我使用了上面的脚本,但是代码无法替换所有文件中的 $ 符号