R-使用正则表达式查找/替换换行符

时间:2019-03-21 15:54:17

标签: r regex

我正在尝试使用正则表达式清除文件夹中的一堆.txt文件。我似乎无法让R找到换行符。

这是我正在使用的代码。它适用于字符替换,但不适用于换行符。

gsub_dir(dir = "folder_name", pattern = "\\n", replacement = "#")

我还尝试了\ r和其他各种排列。使用纯文本编辑器,我发现所有用\ n换行。

1 个答案:

答案 0 :(得分:3)

您无法使用xfun::gsub_dir来做到这一点。

看看source code

  • 使用read_utf8读取文件,该文件基本上执行x = readLines(con, encoding = 'UTF-8', warn = FALSE)
  • 然后,gsub被填充这些行,并且在完成所有替换后,
  • write_utf8 function将行与LF,换行符和符号连接起来。

您需要为此使用一些自定义功能,这是“快速而肮脏的”功能,它将用#替换所有LF符号:

lbr_change_gsub_dir = function(newline = '\n', encoding = 'UTF-8', dir = '.', recursive = TRUE) {
 files = list.files(dir, full.names = TRUE, recursive = recursive)
 for (f in files) {
   x = readLines(f, encoding = encoding, warn = FALSE)
   cat(x, sep = newline, file = f)
 }
}

folder <- "C:\\MyFolder\\Here"
lbr_change_gsub_dir(newline="#", dir=folder)

如果您希望能够匹配多行模式,请pastecollapenewline配合使用,并使用您喜欢的任何模式:

lbr_gsub_dir = function(pattern, replacement, perl = TRUE, newline = '\n', encoding = 'UTF-8', dir = '.', recursive = TRUE) {
 files = list.files(dir, full.names = TRUE, recursive = recursive)
 for (f in files) {
   x <- readLines(f, encoding = encoding, warn = FALSE)
   x <- paste(x, collapse = newline)
   x <- gsub(pattern, replacement, x, perl = perl)
   cat(x, file = f)
 }
}

folder <- "C:\\1"
lbr_gsub_dir("(?m)\\d+\\R(.+)", "\\1", dir = folder)

这将删除仅数字行之后的行。

相关问题