Skip to content

Instantly share code, notes, and snippets.

@HughParsonage
Created December 22, 2017 11:48
Show Gist options
  • Save HughParsonage/b0a6a11b2a2c2e2ab6018164a9b32117 to your computer and use it in GitHub Desktop.
Save HughParsonage/b0a6a11b2a2c2e2ab6018164a9b32117 to your computer and use it in GitHub Desktop.
#' Quickly count the number of files in a directory
number_of_files <- function(dir, filetype = "*.*") {
if (.Platform$OS.type == "windows" &&
nzchar(Sys.which("powershell"))) {
current_wd <- getwd()
on.exit(setwd(current_wd))
setwd(dir)
result <- system2("powershell",
args = c("-command", "Write-Host (dir . | measure).Count;"),
stdout = TRUE,
stderr = "")
# The following is faster via powershell but I can't invoke it
# result <- system2("powershell",
# args = c("-command", '[System.IO.Directory]::GetFiles(".", "*.*").Count'))
setwd(current_wd)
} else {
current_wd <- getwd()
on.exit(setwd(current_wd))
setwd(dir)
result <- system("ls | wc -l", intern = TRUE)
setwd(current_wd)
}
result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment