Pete
Pete

Reputation: 321

Using list.files() how can I get file names that start with a pattern, not that simply contain the pattern?

I am using list.files() to list the files in a directory. However, many of the files contain similar strings, but are in a different group.

write.csv(mtcars, "test1.csv")
write.csv(mtcars, "test2.csv")
write.csv(mtcars, "another_test1.csv")
write.csv(mtcars, "another_test2.csv")

### list files 
pattern_text <- c("test")
list.files(pattern = pattern_text)

[1]  "another_test1.csv" "another_test2.csv"         
[3]        "test1.csv"         "test2.csv"

But I'd like it to grab the files whose names START with "test" not just simply contain "test" in the name. If I use the code as it is, I get all the file names with "test" in it.

I want to end up with only test1.csv and test2.csv

Upvotes: 0

Views: 270

Answers (1)

cristian-vargas
cristian-vargas

Reputation: 769

if you want only the files that start with "test", you can use regular expressions (regex) inside of the pattern= argument of list_files(). If you want to learn more about regex, you can call ?regex in the R console. In this case, adding the metacharacter ^ (a caret) to your code gets the desired result.

write.csv(mtcars, "test1.csv")
write.csv(mtcars, "test2.csv")
write.csv(mtcars, "another_test1.csv")
write.csv(mtcars, "another_test2.csv")

### list files 
list.files(pattern = "^test")
[1] "test1.csv" "test2.csv"

In this case, the ^ symbol is a meta-character that matches the empty string at the beginning of a line. That way, only file names that have nothing before "test" will show up (e.g., "testing" would show up but "attest" would not).

Upvotes: 2

Related Questions