Skip to content

Instantly share code, notes, and snippets.

@lauratboyer
Last active December 15, 2015 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lauratboyer/5243372 to your computer and use it in GitHub Desktop.
Save lauratboyer/5243372 to your computer and use it in GitHub Desktop.
## file-scan.r ## Function to find a pattern in files with user-defined extension (.r by default), ## optional fpattern exact match to file name. ## Search directory is working directory by default but can be set with dir. ## Returns file name and approximate row matches if positive.
## file-scan.r
## Function to find a pattern in files with user-defined extension (.r by default)
## Returns file name and approximate row matches if positive.
## -------------------------------------------------------
## Author: Laura Tremblay-Boyer (l.boyer@fisheries.ubc.ca)
## Written on: March 26, 2013
## Time-stamp: <2013-03-26 16:19:28 Laura>
file.scan <- function(pattern, dir=getwd(), fpattern=NA, ftype=".r") {
nfiles <- list.files(dir,full.names=TRUE)
if(!is.na(fpattern)) nfiles <- nfiles[grep(fpattern, nfiles)]
if(!(ftype=="all")) nfiles <- nfiles[grep(sprintf("%s$",ftype),nfiles)]
if(length(nfiles)==0) print("No files found")
sfunk <- function(wf) {
ss <- scan(wf, "character", sep="\n", blank.lines.skip=FALSE)
gf <- grep(pattern, ss)
if(length(gf)>0) {
return(list("filename"=wf, "row.numbers"=gf))
}else{return(NULL)}
}
fs <- sapply(nfiles, sfunk)
fs <- fs[!sapply(fs,is.null)]
return(fs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment