Rstudio 的“在文件中查找”有 R 版本吗?

RBA*_*RBA 5 r rstudio

我喜欢 Rstudio 的“在文件中查找”功能,您可以在指定目录中的所有文件中搜索文本,但我讨厌指定要搜索的目录和文件类型的方式,您必须单击并指向,呃!

有谁知道在 R 控制台中执行此操作的简单方法?

hrb*_*str 4

fif <- function(what, where=".", in_files="\\.[Rr]$", recursive = TRUE,
                ignore.case = TRUE) {

  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)")

}
Run Code Online (Sandbox Code Playgroud)

跑步

> fif("map")
Run Code Online (Sandbox Code Playgroud)

在我的包顶层的控制台中gdns结果是:

> fif("map")
Run Code Online (Sandbox Code Playgroud)

在控制台中。

如果没有找到匹配的文件,what它会告诉您:

R/dkim.r
   11: #'   purrr::map_df(dkim_rec, .parse_dkim)
   21: #'       purrr::map_df(~{
R/gdns-package.r
   29: #' @importFrom purrr safely map map_df %||% %>%
R/gdns.r
  102:   results <- map(entities, gdns::query, type=type, edns_client_subnet=edns_client_subnet)
  103:   map_df(results, "Answer")
R/spf.r
   11:   purrr::map(spf_rec, .split_spf)
   76:   purrr::map(split_spf(spf_rec), function(x) {
   84:   purrr::map(split_spf(spf_rec), function(x) {
   92:   purrr::map(split_spf(spf_rec), function(x) {
  100:   purrr::map(split_spf(spf_rec), function(x) {
  108:   purrr::map(split_spf(spf_rec), function(x) {
Run Code Online (Sandbox Code Playgroud)

将该函数保留在您的中~/.Rprofile,它将出现在所有非普通 R 会话中。