0
#Move files using part of filenames
#k:/LST_Day_CMG/TEST

library(stringr)
#Get all files
path <- 'k:/WF/LST/Surf_Temp_Monthly_005dg_v6/LST_Day_CMG/TEST'
#001
files <- list.files(path= path, pattern ="001_20*", recursive = TRUE)

move.file <- function(filename,to = '001') {
  fromdir <- dirname(filename)
  rootdir <- dirname(fromdir)
  filebase <- basename(filename)
  # File not in right directory
  if (str_detect(filebase, regex(to, ignore_case = TRUE))&
      !str_detect(fromdir, regex(to, ignore_case = TRUE))) {
    dir.create(file.path(rootdir,to),showWarnings = F)
    file.rename(from = file.path(path,filename),
                to = file.path(path,rootdir,to,filebase))
  } else {F}
}
lapply(files, move.file, to=c("001"))

#032
files <- list.files(path= path, pattern ="032_20*", recursive = TRUE)

move.file <- function(filename,to = '032') {
  fromdir <- dirname(filename)
  rootdir <- dirname(fromdir)
  filebase <- basename(filename)
  # File not in right directory
  if (str_detect(filebase, regex(to, ignore_case = TRUE))&
      !str_detect(fromdir, regex(to, ignore_case = TRUE))) {
    dir.create(file.path(rootdir,to),showWarnings = F)
    file.rename(from = file.path(path,filename),
                to = file.path(path,rootdir,to,filebase))
  } else {F}
}
lapply(files, move.file, to=c("032"))

AND SO ON... TILL 335

I find Code here, and try to modify it.

I used pattern argument for moving some specific files named DOY (day of observation), 001 to 335 file name to 001 to 335 folder names. But I'm running it by changing the folder and pattern name. Is there any function to automatize it from 001 to 335 in one click? Thank you

user438383
  • 5,716
  • 8
  • 28
  • 43

1 Answers1

0

Using sprintf should do the trick.

library(stringr)
#Get all files
path <- 'k:/WF/LST/Surf_Temp_Monthly_005dg_v6/LST_Day_CMG/TEST'

files <- list.files(path= path, pattern ="[0-9]{3}_20*", recursive = TRUE)

move.file <- function(filename,to = '001') {
  fromdir <- dirname(filename)
  rootdir <- dirname(fromdir)
  filebase <- basename(filename)
  # File not in right directory
  if (str_detect(filebase, regex(to, ignore_case = TRUE))&
      !str_detect(fromdir, regex(to, ignore_case = TRUE))) {
    dir.create(file.path(rootdir,to),showWarnings = F)
    file.rename(from = file.path(path,filename),
                to = file.path(path,rootdir,to,filebase))
  } else {F}
}

for (i in seq_along(files)){
     move.file(filename = files[i], to =sprintf("%03d",i))
}
tacoman
  • 882
  • 6
  • 10