Reputation: 467
I want to use list.files of R to list files containing this pattern "un[a digit]" such as filename_un1.txt, filename_un2.txt etc... Here is the general code:
list_files <- list.files(path="my_file_path", recursive = TRUE, pattern = "here I need help", full.names = TRUE)
I have tried putting un\d
in the pattern input but does not work.
Upvotes: 3
Views: 4187
Reputation: 627292
You should bear in mind that in R, strings allow using escape sequences. However, the regex engine needs a literal \
to pass shorthand character classes (like \d
for digits) or to escape special chars (like \\.
to match a literal dot.)
So, you need
pattern = "_un\\d+\\.txt$"
where
_un
- matches a literal substring _un
\\d+
- matches 1 or more digits (as +
is a one or more quantifier)\\.
- matches a literal dottxt
- matches a literal sequence of characters txt
$
- end of string.Upvotes: 7
Reputation: 946
list_files <- list.files(path="my_file_path", recursive = TRUE, pattern = "un[0-9]", full.names = TRUE)
Upvotes: 1