English 中文(简体)
我如何用 R 重命名文件?
原标题:How do I rename files using R?

I have over 700 files in one folder named as: files from number 1 to number9 are named for the first month:

water_200101_01.img  
water_200101_09.img  

从10号到30号的文件被命名为:

water_200101_10.img
water_200101_30.img

And so on for the second month: files from number 1 to number9 are named:

water_200102_01.img  
water_200102_09.img  

从10号到30号的文件被命名为:

water_200102_10.img
water_200102_30.img 

如何重新命名它们而不对文件做任何更改 。 请更改名称, 例如 Name

water_1
water_2
...till...
water_700
最佳回答

file.rename 将会重命名文件, 它可以从 和 名称同时获取 的矢量。

比如说:

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

可能工作。

如果具体关心顺序, 您可以对当前存在的文件列表进行排序, 或者按照特定模式进行排序, 只要直接创建文件名矢量( 虽然我注意到700不是30的倍数) 。

我将撇开这个问题,“你为什么想这样做?” 因为你似乎把文件名中的信息丢弃了, 但大概这个信息也包含在别处。

问题回答

如果您想要替换文件名称中与给定模式和另一个模式匹配的某个部分。 这对同时重命名多个文件有用。 例如, 此代码将包含 Foo 的文件全部取用, 并在文件名称中以 bob 替换 foo 。

file.rename(list.files(pattern = "foo"), str_replace(list.files(pattern = "foo"),pattern = "foo", "bob"))

我为我自己写了这个。 它很快, 允许 Regex 查找和替换, 能够忽略文件的后缀, 并且可以显示在“ 审判运行” 中会发生什么, 并且可以保护现有文件不被覆盖 。

如果您在 Mac 上, 它可以使用苹果脚本来选择在“ 查找者” 中当前文件夹作为目标文件夹 。

umx_rename_file <- function(findStr = "Finder", replaceStr = NA, baseFolder = "Finder", test = TRUE, ignoreSuffix = TRUE, listPattern = NULL, overwrite = FALSE) {
    umx_check(!is.na(replaceStr), "stop", "Please set a replaceStr to the replacement string you desire.")

    # ==============================
    # = 1. Set folder to search in =
    # ==============================
    if(baseFolder == "Finder"){
        baseFolder = system(intern = TRUE, "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)
    }

    # =================================================
    # = 2. Find files matching listPattern or findStr =
    # =================================================
    a = list.files(baseFolder, pattern = listPattern)
    message("found ", length(a), " possible files")

    changed = 0
    for (fn in a) {
        if(grepl(pattern = findStr, fn, perl= TRUE)){
            if(ignoreSuffix){
                # pull suffix and baseName (without suffix)
                baseName = sub(pattern = "(.*)(\..*)$", x = fn, replacement = "\1")
                suffix   = sub(pattern = "(.*)(\..*)$", x = fn, replacement = "\2")
                fnew = gsub(findStr, replacement = replaceStr, x = baseName, perl= TRUE) # replace all instances
                fnew = paste0(fnew, suffix)
            } else {
                fnew = gsub(findStr, replacement = replaceStr, x = fn, perl= TRUE) # replace all instances
            }
            if(test){
                message(fn, " would be changed to:  ", omxQuotes(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(paste0(baseFolder, fn), paste0(baseFolder, fnew))
                    changed = changed + 1;
                }
            }
        }else{
            if(test){
                # message(paste("bad file",fn))
            }
        }
    }
    if(test & changed==0){
        message("set test = FALSE to actually change files.")
    } else {
        umx_msg(changed)
    }
}

下面是我用简单的基本代码 在一个指定的目录中 进行序列匹配和更改所有文件名的工作

old_files <- list.files(path = ".", pattern="water_*.img$")

# Create df for new files
new_files <- data.frame()

for(i in 1:length(old_files)){
new_files <- append(paste0(path = ".", substr(old_files[i], 1,6),"water_",i,".img"), new_files)
}

new_files <- as.character(new_files)

# Copy from old files to new files

file.rename(from = old_files), to = as.vector(new_files)




相关问题
How to plot fitted model over observed time series

This is a really really simple question to which I seem to be entirely unable to get a solution. I would like to do a scatter plot of an observed time series in R, and over this I want to plot the ...

REvolution for R

since the latest Ubuntu release (karmic koala), I noticed that the internal R package advertises on start-up the REvolution package. It seems to be a library collection for high-performance matrix ...

R - capturing elements of R output into text files

I am trying to run an analysis by invoking R through the command line as follows: R --no-save < SampleProgram.R > SampleProgram.opt For example, consider the simple R program below: mydata =...

R statistical package: wrapping GOFrame objects

I m trying to generate GOFrame objects to generate a gene ontology mapping in R for unsupported organisms (see http://www.bioconductor.org/packages/release/bioc/vignettes/GOstats/inst/doc/...

Changing the order of dodged bars in ggplot2 barplot

I have a dataframe df.all and I m plotting it in a bar plot with ggplot2 using the code below. I d like to make it so that the order of the dodged bars is flipped. That is, so that the bars labeled "...

Strange error when using sparse matrices and glmnet

I m getting a weird error when training a glmnet regression. invalid class "dgCMatrix" object: length(Dimnames[[2]]) must match Dim[2] It only happens occasionally, and perhaps only under larger ...

Generating non-duplicate combination pairs in R

Sorry for the non-descriptive title but I don t know whether there s a word for what I m trying to achieve. Let s assume that I have a list of names of different classes like c( 1 , 2 , 3 , 4 ) ...

Per panel smoothing in ggplot2

I m plotting a group of curves, using facet in ggplot2. I d like to have a smoother applied to plots where there are enough points to smooth, but not on plots with very few points. In particular I d ...