1

I would like to list all files in a directory that have "xyz" at the beginning and the first underscore has a 2 after it.

For example, xyzfjd_2_34_1.png, xyz-39_2dog.jpg would work, whereas xyzdog_3_dog.png would not work.

I tried

list.files(dir, pattern="^xyz*_2*");

which is clearly wrong, mostly because I don't even know what I'm doing...

CodeGuy
  • 28,427
  • 76
  • 200
  • 317

1 Answers1

3

Do file names without an underscore match? I am assuming no.

I think you are interpreting * for any character. Instead, . is any character. * is "0 or more times". So your pattern ^xyz*_2* can match xy_ and xyzzzz_222. It won't match xyz1_2.

Try:

list.files(dir, pattern = "^xyz[^_]*_2")
  • ^ Beginning of the file name
  • xyz
  • [^_]* Any combination of characters that is not _ (including the empty string)
  • _2, an underscore followed by a two.

I don't worry about the rest of the name because the pattern only needs to match part of the file name.

Blue Magister
  • 13,044
  • 5
  • 38
  • 56