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

Time:06-09

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 ?

CodePudding user response:

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)
  •  Tags:  
  • r
  • Related