我有一个文件夹中超过700个文件,命名为:从1号到number9被命名为第一个月的文件:
water_200101_01.img
water_200101_09.img
从10号到number30文件被命名为:
water_200101_10.img
water_200101_30.img
等第二个月:从1号文件number9被命名为:
water_200102_01.img
water_200102_09.img
从10号到number30文件被命名为:
water_200102_10.img
water_200102_30.img
我怎样才能无需对文件进行任何更改将其重命名。 只是改变了NAMS,例如
water_1
water_2
...till...
water_700
file.rename
将重命名文件,并且它可以采取两者的矢量from
和to
名字。
因此,像:
file.rename(list.files(pattern="water_*.img"), paste0("water_", 1:700))
可能工作。
如果有关订单的护理具体而言,您既可以梳理目前存在的,或者如果他们遵循一个特定的模式,只需直接创建文件名的载体(虽然我注意到,700不是30的倍数)的文件列表。
我将拨出的问题,“为什么你要?” 因为你似乎在文件名被扔掉的信息,但据推测这些信息在其他地方包含为好。
我写了这个自己。 它是快速,允许在正则表达式查找和替换,并且支持“试运行”。
如果你是在Mac上,它可以使用的AppleScript在Finder中挑选出当前文件夹作为目标文件夹。
umxRenameFile <- function(baseFolder = "Finder", findStr = NA, replaceStr = NA, listPattern = NA, test = T, overwrite = F) {
# uppercase = u$1
if(baseFolder == "Finder"){
baseFolder = system(intern = T, "osascript -e 'tell application \"Finder\" to get the POSIX path of (target of front window as alias)'")
message("Using front-most Finder window:", baseFolder)
} else if(baseFolder == "") {
baseFolder = paste(dirname(file.choose(new = FALSE)), "/", sep = "") ## choose a directory
message("Using selected folder:", baseFolder)
}
if(is.na(listPattern)){
listPattern = findStr
}
a = list.files(baseFolder, pattern = listPattern)
message("found ", length(a), " possible files")
changed = 0
for (fn in a) {
findB = grepl(pattern = findStr, fn) # returns 1 if found
if(findB){
fnew = gsub(findStr, replace = replaceStr, fn) # replace all instances
if(test){
message("would change ", fn, " to ", fnew)
} else {
if((!overwrite) & file.exists(paste(baseFolder, fnew, sep = ""))){
message("renaming ", fn, "to", fnew, "failed as already exists. To overwrite set T")
} else {
file.rename(paste(baseFolder, fn, sep = ""), paste(baseFolder, fnew, sep = ""))
changed = changed + 1;
}
}
}else{
if(test){
# message(paste("bad file",fn))
}
}
}
message("changed ", changed)
}