如何在 R 代码中搜索不同文件格式(包括 .Rmd)的字符串

问题描述 投票:0回答:1

如何调整此功能以搜索 .R 和 .Rmd 文件并查看注释部分,例如#### ?

UFif <- function(what, where=".", in_files="\\.[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)")
  })
}
r full-text-search
1个回答
0
投票

此版本查看 .R 和 .Rmd 文件,并且可以限制为仅检查注释行:

UFifv2 <- function(what, where=".", in_files="\\.(R|r|Rmd|rmd)$", 
                    recursive = FALSE, ignore.case = TRUE, comments.only=FALSE) {
  suppressWarnings({
  fils <- list.files(path = where, pattern = in_files, recursive = recursive)
  print(fils)
  cat("\n Searching...\n")
  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
    }
    
    if(comments.only == FALSE) {
      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(comments.only == TRUE) {
      contents <- readLines(fil)
      contents <- contents[grepl('^#', contents)]
      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)")
  })
}


UFifv2("dplyr")
UFifv2("dplyr", comments.only=TRUE)
© www.soinside.com 2019 - 2024. All rights reserved.