[英]R - find/replace line breaks using regex
我正在尝试使用正则表达式清理文件夹中的一堆 .txt 文件。 我似乎无法让 R 找到换行符。
这是我正在使用的代码。 它适用于字符替换,但不适用于换行符。
gsub_dir(dir = "folder_name", pattern = "\\n", replacement = "#")
我也试过 \\r 和其他各种排列。 使用纯文本编辑器,我找到所有带有 \\n 的换行符。
你不能用xfun::gsub_dir
做到这xfun::gsub_dir
。
看看源代码:
read_utf8
读取文件,它基本上执行x = readLines(con, encoding = 'UTF-8', warn = FALSE)
,gsub
被输入这些行,当所有替换完成后,write_utf8
函数将行...与 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)
如果您希望能够匹配多行模式,请paste
用newline
collape
它们的newline
并使用您喜欢的任何模式:
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)
这将删除仅数字行之后的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.