Last active
December 15, 2015 10:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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,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