Reputation: 2785
Completely stumped, though it seems like a simple question that will be voted down very shortly as a duplicate, but I couldn't find the right "pattern" to search for the answer.
I am looking for files in a folder that match a dual pattern and then want to open them in R. So, assume list.files
produces the following:
lf <- c("foo_23_bar.txt", "goo_42_mar.txt", "boo_42_bar.txt")
In command line, I would use ls foo*bar
to find the first file, but in R, something like,
grep(paste("foo","bar",sep="|"),lf)
returns both files 1 and 3. I am not sure how to use the perl=TRUE
option. Any help would be great. Thanks!
Upvotes: 1
Views: 199
Reputation: 2785
Hmm .. one of the useful answers has disappeared. Anyway, here is exactly what I had in mind, combining Martin's and Michael's(?) answers:
list.files(path="data/",pattern=glob2rx("*foo*bar*"))
Or, as solved by Bingjun:
lf <- system("ls data/*foo*bar*")
This has the added benefit of providing filenames with path, making it simpler to read them into R directly.
Upvotes: 0
Reputation: 56
I usually use the system function. Check out here. http://stat.ethz.ch/R-manual/R-patched/library/base/html/system.html
Upvotes: 3
Reputation: 46876
Use glob2rx
to get the corresponding regex
> glob2rx("foo*bar*")
[1] "^foo.*bar"
and
> grep(glob2rx("foo*bar*"), lf, value=TRUE)
[1] "foo_23_bar.txt"
Upvotes: 4