Skip to content

Instantly share code, notes, and snippets.

@mattjbayly
Created August 12, 2016 15:37
Show Gist options
  • Save mattjbayly/ffa400a75e18732ad221506a2150bc9b to your computer and use it in GitHub Desktop.
Save mattjbayly/ffa400a75e18732ad221506a2150bc9b to your computer and use it in GitHub Desktop.
Find the occurence and count of occurence for a text string across php files
#' Find the occurence and count of occurence for a text string across php files.
#'
#' @param path A path directory to search in containing php files of interest.
#' @param files A list of files to search within.
#' @param search_for A text string to search for within php files.
#' @return The count of \code{search_for} occurences across php \code{files}.
#' @examples
#' # Define main root directories to search within
#' foldergroup <- "C:/Users/me/Desktop"
#' # Specify the phrase to search for
#' phrase <- 'thisIsMyPatternOfInterest'
#' # Search within php files for string
#' Find_Php_String_In_Php_Files(path = foldergroup, files = list.files(path = classes, pattern = ".php"), search_for=phrase)
Find_Php_String_In_Php_Files <- function(path = getwd(),files = "",search_for){
if(length(files) == 1){
# single file readlines
suppressWarnings(mylines <- readLines(paste0(path, "/", files), n = -1))
countoccure <- length(grep(search_for, mylines))
return(print(paste0(search_for, " occured ", countoccure, " times in ", files)))
}
if(length(files) > 1){
allfiles <- list.files(path = path, pattern = ".php")
all_lines_all_files = lapply(allfiles, function(x) {
mylines <- readLines(paste0(path, "/", x), n = -1)
return(mylines)})
files_with_pattern <- lapply(all_lines_all_files, function(x){grep(search_for, x)})
names(files_with_pattern) <- allfiles
summary_files <- lengths(files_with_pattern, use.names = TRUE)
return(summary_files[summary_files>0])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment