Skip to content

Instantly share code, notes, and snippets.

@aammd
Forked from lauratboyer/file-scan.r
Created July 24, 2013 18:07
Show Gist options
  • Save aammd/6072983 to your computer and use it in GitHub Desktop.
Save aammd/6072983 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)
## Returns file name and approximate row matches if positive.
## -------------------------------------------------------
## Author: Laura Tremblay-Boyer ([email protected])
## 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)
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