Haribo
Haribo

Reputation: 2226

list.files() on a specific sub-directory in a folder tree

I have a huge folder structure like :

main
  |____ A1
  |     |__proj_doc
  |            |__ some txt files
  |____ B2
  |     |__proj_doc
  |            |__ some txt files
  |____ C3
        |__proj doc
               |__ tmp
               |    |__ some txt files
               | 
               |__ some txt files
               
  

and would like to list all the txt files from all proj_doc and proj doc folders.

mylist <-list.files(path = "/main", recursive = TRUE,
                            pattern = "\\.txt$", 
                            full.names = TRUE)

will list all the files but from the root main folder, including all the sub folders, which cause a lot of unnecessary data. How could I correct the path to just look into correct sub-directories ?

Upvotes: 1

Views: 804

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545578

Here’s one way:

dirs = list.dirs('main')
proj_doc_dirs = grep('/proj./proj[ _]doc', dirs, value = TRUE)
txt_files = dir(proj_doc_dirs, pattern = '\\.txt$', full.names = TRUE)

Upvotes: 3

Related Questions