按文件名移动文件

Moving files by their filenames

#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

这里找到了,尝试修改

我使用模式参数将一些名为 DOY(观察日)的特定文件从 001 到 335 文件名移动到 001 到 335 文件夹名。但是我 运行 它是通过更改文件夹和模式名称来实现的。有什么功能可以一键自动从001变成335吗? 谢谢

使用 sprintf 应该可以解决问题。

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))
}