I have a fs path character vector with a list of file names like these:
path/to/folder/output_1_CR.csv
path/to/folder/output_2_CR.csv
...
path/to/folder/output_22_CR.csv
...
path/to/folder/output_67_CR.csv
Here's the code I used to read in these output files into a fs path character vector:
CR_A_paths <- fs::dir_ls(path = "/path/to/folder", regexp = "[CR].csv$")
I want to update the names of the files with single digits in their file name (e.g. output_1_CR.csv, output_5_CR.csv) such that there's a 0 before the single digit (i.e. output_1_CR.csv becomes output_01_CR.csv)
Any idea on efficient ways to do so?
Thanks!
You could use str_replace
:
to <- stringr::str_replace(CR_A_paths, "\\d+", ~sprintf("%02d", as.numeric(.x)))
to
[1] "path/to/folder/output_01_CR.csv" "path/to/folder/output_02_CR.csv"
[3] "path/to/folder/output_22_CR.csv" "path/to/folder/output_67_CR.csv "
Now to update the names use:
file.rename(CR_A_paths,to)
CR_A_paths <- c("path/to/folder/output_1_CR.csv", "path/to/folder/output_2_CR.csv",
"path/to/folder/output_22_CR.csv", "path/to/folder/output_67_CR.csv "
)