如何调整R函数以搜索.R、.Rmd文件及注释内容
修改后的UFif函数
UFif <- function(what, where=".", in_files="\\.([Rr]md|[Rr])$", recursive = TRUE, ignore.case = TRUE) { suppressWarnings({ fils <- list.files(path = where, pattern = in_files, recursive = recursive) found <- FALSE file_cmd <- Sys.which("file") for (fil in fils) { if (nchar(file_cmd) > 0) { ftype <- system2(file_cmd, fil, TRUE) if (!grepl("text", ftype)[1]) next } contents <- readLines(fil) res <- grepl(what, contents, ignore.case = ignore.case) res <- which(res) if (length(res) > 0) { found <- TRUE cat(sprintf("%s\n", fil), sep="") cat(sprintf(" % 4s: %s\n", res, contents[res]), sep="") } } if (!found) message("(No results found)") }) }
修改说明
- 支持.Rmd文件:将
in_files参数的默认正则表达式从\\.[Rr]$改为\\.([Rr]md|[Rr])$,可匹配所有.R、.r、.Rmd、.rmd格式的文件,也可以用等价的\\.[Rr](md)?$实现相同效果。 - 检索####注释内容:原函数会读取文件的所有行内容(包括以
####开头的注释行),并对每一行执行字符串匹配,因此无需额外修改逻辑——只要目标字符串出现在注释行中,就会被检索到。
内容的提问来源于stack exchange,提问作者highbury
相关产品推荐
相关产品推荐

