Search code examples
rdirectorymovecreate-directorymovefile

Create folder based on filename


I have a question how to create a new folder based on part of the filename and also move directly the corresponding files to the new folder. Below you will find the structure of my directory with some examples. In both D0 and D1 folders you will find Weather and Day folder that contains .TIF files. What I would like is that inside the brightfield and FITC folders folders are created that are based partially on the filename. For example if the file contains s2, then a folder S2 is created with the file that has S2 in his name.

Currently the situation

main Directory
    |
    |___ Experiment
            ├── D0
               ├── Weather
                       |__ D0_PM_flow__Weather 100 - CAM_s3_t5.TIF
                       |__ D0_PM_flow__Weather 100 - CAM_s3_t5.TIF
                       
            │  └── Temperature
               
            └── D1
               ├── Weather
               └── Temperature

What I would like:

main Directory
        |
        |___ Experiment
                ├── D0
                   ├── Weather
                           |__ S1
                                | D0_PM_flow__Weather 100.txt
                           |__ S2
                                |D0_PM_flow__Weather 100.txt
                           
                │  └── Temperature
                   
                └── D1
                   ├── Weather
                   └── Temperature

I can do this manually with the code below, but that takes a lot of time. Is there a more convenient way to do this more automatically? For convenience I only showed 3 files in the D0/Weather folder, but there are also files in the D0/Temperature folder, D1/Weather and D1/Temperature where I also want to create folders such as S1,S2 etc.. Furthermore, some folders have only three groups, so S1- S3, while other groups have S1- S6.


Solution

  • Recycling some code:

    library(stringr)
    #Get all files
    path <- 'C:/temp/test'
    files <- list.files(path= path, recursive = TRUE)
    
    move.file <- function(filename) {
      (fromdir <- dirname(filename))
      (filebase <- basename(filename))
      dir.match <- toupper(str_extract(filename,'_[Ss][0-9]+_'))
      if (isTRUE(nchar(dir.match)>0)) {
        dir.match <- substr(dir.match,2,nchar(dir.match)-1)
        # File not in right directory
        if (basename(fromdir)!=dir.match) {
          dir.create(file.path(path,fromdir,dir.match),showWarnings = F)
          file.rename(from = file.path(path,filename),
                      to = file.path(path,fromdir,dir.match,filebase))
        }
      }  else {F}
    }
    
    lapply(files, move.file)