Finding specific terms in several files.

#5
The scenario is as follows: assume we have a folder C:\Desktop\test. There have 8 files, data1.txt, .... data8.txt, under this folder. Some of these files may contain a specific term, e.g., colorcoding. I would like to know how many files contain this specific term, and which are them. This can be done under Unix/Linux using shell command. But I need to know how to do that within R program. Thanks.
 

Dason

Ambassador to the humans
#6
Code:
filegrep <- function(filename, pattern){
    any(grepl(pattern, readLines(filename)))
}

path <- "C:/Desktop/test"
pat <- "colorcoding"
out <- sapply(dir(path), filegrep, pattern = pat)
which(out)
 
#7
Dason, thanks for the code. I tried, and it gives me the following error message

Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") : cannot open file 'data1.txt': No such file or directory
However, the data1.txt is contained in the folder

Code:
filegrep <- function(filename, pattern){
    any(grepl(pattern, readLines(filename)))
}

path <- "C:/Desktop/test"
pat <- "colorcoding"
out <- sapply(dir(path), filegrep, pattern = pat)
which(out)
 

Dason

Ambassador to the humans
#8
Ah. I overlooked something and tried to make the function more general without actually trying it out after generalizing it.

Code:
filegrep <- function(filename, pattern){
    any(grepl(pattern, readLines(filename)))
}

path <- "C:/Desktop/test"
setwd(path)
pat <- "colorcoding"
out <- sapply(dir(), filegrep, pattern = pat)
which(out)
I was making an implicit assumption that the folder of interest was the working directory in my filegrep function.