是否有R版的Rstudio'在文件中查找'?

时间:2017-08-04 08:37:04

标签: r rstudio

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

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

2 个答案:

答案 0 :(得分:3)

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

}

运行

> fif("map")

在我的gdns包的顶层控制台中导致:

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

在控制台中。

如果找不到与what匹配的文件,则会告诉您:

> fif("python")
(No results found)

将此功能保留在~/.Rprofile中,并且它将在所有非香草R会话中。

答案 1 :(得分:0)

我刚刚完成了一个用于在某些文件中查找模式的软件包:findInFiles(尚未完成,但很快)。

要搜索的模式是一个正则表达式。您可以控制搜索的深度,并且可以区分大小写。结果显示在RStudio查看器中(实际上是htmlwidget)。

它需要grep命令行实用程序,该实用程序在Linux平台上始终可用;在Windows上,我认为它是在安装git时安装的。

remotes::install_github("stla/findInFiles")

enter image description here