Home > database >  using length > 1 of a file name when rename files with seq_along?
using length > 1 of a file name when rename files with seq_along?

Time:08-06

I'm trying to rename files in a folder which have the same names but each has a unique number added. The numbers are in order but they have 5 or 6 digits so when I rename them with "seq_along" and "file_rename" to a simple numeric sequence the code considers only the first digit and the ones that start with 10xxx will be the first ones instead of the ones that start with 8xxx, 9xxx. I want them to look like 1 (1).jpg, 1 (2).jpg, etc., but with the original order.

This is how my file names are in the folder:

"Name8000.jpg", "Name9000.jpg", "Name10000.jpg", "Name11000.jpg"

I would like to change the names in the following way:

"Name8000.jpg" = "1 (1).jpg"
"Name9000.jpg" = "1 (2).jpg" 
"Name10000.jpg" = "1 (3).jpg" 
"Name11000.jpg" = "1 (4).jpg"

Here is the code that I use:

files <- list.files(pattern = "*.jpg", full.names = T)
sapply(seq_along(files),function(x){file.rename(files[x],paste0("1 (", x, ").jpg"))})

And with this, this is what I get:

"Name8000.jpg" = "1 (3).jpg"
"Name9000.jpg" = "1 (4).jpg"
"Name10000.jpg" = "1 (1).jpg"
"Name11000.jpg" = "1 (2).jpg"

CodePudding user response:

Here's an illustration of using gtools::mixedsort. It's a bit of a black box solution for me. But it should get the result you want with a lot less effort.

# Set up files so that it matches your example
files <- c("Name8000.jpg", 
           "Name9000.jpg", 
           "Name10000.jpg", 
           "Name11000.jpg")
files <- sort(files)



library(gtools)

# Demonstrate `mixedsort`
mixedsort(files)

# reorder the filenames
files <- mixedsort(files)

# apply your sapply code.
sapply(seq_along(files), 
       function(x) file.rename(files[x], paste0("1 (", x, ").jpg")))

CodePudding user response:

I found a solution, although it's not very elegant. First, I remove the Name with this code:

file.rename(list.files(pattern = ".jpg"),
            str_replace(list.files(pattern = ".jpg"), "Name", ""))

This way I get these names:

"8000.jpg", "9000.jpg", "10000.jpg", "11000.jpg"

Then I use the "str_pad" function from "stringr" to fill up the string with a 0 on the left, if it's only 8 character long:

file.rename(list.files(pattern = ".jpg"),
            str_pad(list.files(pattern = ".jpg"), 9, side="left", pad="0"))

This way the names look like this:

"08000.jpg", "09000.jpg", "10000.jpg", "11000.jpg"

And finally I use the original code to sequence the files:

files <- list.files(pattern = "*.jpg", full.names = T) 
sapply(seq_along(files),function(x){file.rename(files[x],paste0("1 (", x, ").jpg"))})

In this way I get the files named by a numeric sequence in the required order.

  • Related