Rime
Rime

Reputation: 942

using list.files() in R to find files that start with a specific string

I am using list.files() in r to read in files. However, the pattern= input will scan all files that contain that special string I am scanning for...

Ex.

MASTERLIST =list.files("/Volumes/3TB/",pattern="CL")

will call in the following files:

[1] "CLF16"  "CLF17"  "CLF18"  "CLF19"  "CLG16"  "CLG17"  "CLG18"  "CLH16"  "CLH17"  "CLJ16"  "CLJ17"  "CLK16"  "CLK17"  "CLK18"  "CLM16"  "CLM17" 
[17] "CLM18"  "CLM19"  "CLN16"  "CLN17"  "CLQ16"  "CLQ17"  "CLU15"  "CLU16"  "CLU17"  "CLV15"  "CLV16"  "CLV17"  "CLX15"  "CLX16"  "CLX17"  "CLZ15" 
[33] "CLZ16"  "CLZ17"  "CLZ18"  "CLZ19"  "CLZ20"  "MCLH16" "MCLM16" "MCLU16" "MCLZ16"

But I only want those files that begin with CL and not every file that contains CL like files 38 through 41

How do I get it to call only those files that begin that pattern?

Upvotes: 19

Views: 20460

Answers (2)

sebastian-c
sebastian-c

Reputation: 15415

The pattern argument takes a regex, so you can use: pattern = "^CL"

Upvotes: 26

ClementWalter
ClementWalter

Reputation: 5324

You can use Sys.glob to use wildcard expansion and so to precise what you want:

Sys.glob('CL*')

should do the job you want.

Upvotes: 3

Related Questions