Reputation: 299
I have the following example file in a folder. I'd like to read files having similar name.
If I use list.files(pattern="ABC_.*?\\.csv")
,it would read all the csv
file. What should I change so that it reads only ABC_001.csv
and ABC_012
and similarly the other two.
ABC_001.csv
ABC_001_def.csv
ABC_012.csv
ABC_012_def.csv
Upvotes: 3
Views: 71
Reputation: 887851
Create the pattern
that matches 'ABC' at the start (^
) of the string followed by _
, then a 0
and two digits (\\d{2}
) followed by .
(escape the \\.
as .
is a metacharacter that matches any character) and the 'csv' at the end ($
) of the string
list.files(pattern = '^ABC_0\\d{2}\\.csv$', full.names = TRUE)
If it is 3 digits and not specific to 0 i.e. if we need to match 'ABC_135.csv', remove the 0
and use \\d{3}
i.e. 3 digit
list.files(pattern = '^ABC_\\d{3}\\.csv$', full.names = TRUE)
It can be checked with grep
v1 <- c("ABC_001.csv", "ABC_001_def.csv", "ABC_012.csv", "ABC_012_def.csv")
grep('^ABC_0\\d{2}\\.csv$', v1, value = TRUE)
#[1] "ABC_001.csv" "ABC_012.csv"
Upvotes: 3