【发布时间】:2019-07-14 20:25:42
【问题描述】:
我想从文件中删除所有以特定模式开头的行。我想用 R 来做这个。最好不要先读取整个文件,然后删除所有匹配的行,然后再写入整个文件,因为文件可能很大。因此,我想知道我是否可以同时对 same 文件进行读取和写入连接(一直打开,一次一个?)。下面显示了这个想法(但“挂起”并因此失败)。
## Create an example file
fnm <- "foo.txt" # file name
sink(fnm)
cat("Hello\n## ----\nworld\n")
sink()
## Read the file 'fnm' one line at a time and write it back to 'fnm'
## if it does *not* contain the pattern 'pat'
pat <- "## ----" # pattern
while(TRUE) {
rcon <- file(fnm, "r") # read connection
line <- readLines(rcon, n = 1) # read one line
close(rcon)
if(length(line) == 0) { # end of file
break
} else {
if(!grepl(pat, line)) {
wcon <- file(fnm, "w")
writeLines(line, con = wcon)
close(wcon)
}
}
}
注意:
1) 如果写入新文件,请参阅here 以获得答案。然后可以删除旧文件并将新文件重命名为旧文件,但这似乎不太优雅:-)。
2) 更新:以下MWE产生
Hello
world
-
world
见:
## Create an example file
fnm <- "foo.txt" # file name
sink(fnm)
cat("Hello\n## ----\nworld\n")
sink()
## Read the file 'fnm' one line at a time and write it back to 'fnm'
## if it does *not* contain the pattern 'pat'
pat <- "## ----" # pattern
con <- file(fnm, "r+") # read and write connection
while(TRUE) {
line <- readLines(con, n = 1L) # read one line
if(length(line) == 0) break # end of file
if(!grepl(pat, line))
writeLines(line, con = con)
}
close(con)
【问题讨论】:
标签: r connection readlines