How do I rename files using R?

China☆狼群 提交于 2019-11-26 17:35:50

file.rename will rename files, and it can take a vector of both from and to names.

So something like:

file.rename(list.files(pattern="water_*.img"), paste0("water_", 1:700))

might work.

If care about the order specifically, you could either sort the list of files that currently exist, or if they follow a particular pattern, just create the vector of filenames directly (although I note that 700 is not a multiple of 30).

I will set aside the question, "why would you want to?" since you seem to be throwing away information in the filename, but presumably that information is contained elsewhere as well.

I wrote this for myself. It is fast, allows regex in find and replace, and supports "trial runs".

If you are are on a mac, it can use applescript to pick out the current folder in the Finder as a target folder.

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)
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!