There are similar questions on Stack Overflow but none quite meets my specific needs.
I have a list of files with random names in a subfolder of my working directory, e.g. working_directory/animals/photos
The files are currently named:
Chicken.png
Moose.png
Cat.png
And I would like to rename them into the following (I have 5750 photos):
Animal1.png
Animal2.png
Animal3.png
...
Animal5750.png
I feel like there should be a simple solution but I can't quite figure out the coding for file.rename
to do this, where most examples are for individual files, or files within the working directory.
This is my attempt from looking at examples on Stack Exchange, but this did not work:
original_path <- 'animals/photos'
renamed_list <- dir(path = original_path, pattern = '*.png')
sapply(X = renamed_list, FUN = function(x) {
file.rename(paste0(original_path, x),
paste0(original_path, 'Animal', substring(x, first = 1))) })
Thank you in advance
Here is a function that does what you ask for.
The main problem is to assemble the new names from the old names' path and file extension. This is done with functions
basename
anddirname
in packagebase
;file_ext
andfile_path_sans_ext
in packagetools
.The consecutive numbers are produced by
seq_along
. Thenpaste0
,sprintf
andfile.path
put everything together.If you want all numbers to have the same number of digits, change the format part of the
fmt_string
string to"%04d.%s"
.