2017-08-04 52 views
0

我喜歡Rstudio的'查找文件'功能,您可以在其中搜索指定目錄中所有文件中的文本,但我討厭指定搜索目錄和文件類型的方式,您必須單擊並指向, !Rstudio的「查找文件」是否有R版本?

有沒有人知道在R控制檯這樣做的簡單方法?

+0

只需在windows上使用grep on unix或findstr,通過R的'system'命令調用? – RockScience

+0

你也可以嘗試使用記事本++,我認爲他們有類似的功能 – zwep

回答

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

} 

在我gdns包導致頂層運行

> fif("map") 
在控制檯

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會話。

+0

我試圖在Windows上,它不工作,我認爲這個問題可能在Sys.which命令?試圖在這裏進行調試,但如果您在此期間有一個快速解決方案,我會很感激。對不起,我應該說在哪個系統中我打算使用它,我的壞。 感謝您的答案,但功能看起來很棒! – RBA

+0

嘗試安裝https://cran.r-project.org/bin/windows/Rtools/installer.html,然後嘗試該功能。 – hrbrmstr

相關問題