[R] Rename multiple files in a directory and write renamed files back to directory
Chel Hee Lee
chl948 at mail.usask.ca
Fri Dec 5 05:16:54 CET 2014
I put five data files (example1.dat, example2.dat, example3.dat,
example4.dat, example5.dat, example6.dat) in my working directory.
>
> file_names <- list.files(pattern="*.dat")
> file_names
[1] "example1.dat" "example2.dat" "example3.dat" "example4.dat"
"example5.dat"
[6] "example6.dat"
>
> new_names <- paste("new_example_",
+ formatC(seq(length(file_names)), width=2, flag="0"),
+ ".dat", sep="")
> new_names
[1] "new_example_01.dat" "new_example_02.dat" "new_example_03.dat"
[4] "new_example_04.dat" "new_example_05.dat" "new_example_06.dat"
>
> file.rename(from=file_names, to=new_names)
[1] TRUE TRUE TRUE TRUE TRUE TRUE
> list.files(pattern="*.dat")
[1] "new_example_01.dat" "new_example_02.dat" "new_example_03.dat"
[4] "new_example_04.dat" "new_example_05.dat" "new_example_06.dat"
>
Is this what you are looking for? I hope this helps.
Chel Hee Lee
On 12/04/2014 09:44 PM, Zilefac Elvis via R-help wrote:
> Hello,
> I would like to rename multiple files in a directory. Filenames are read using:
>
> lfile <- list.files(pattern="rcp45_Daily_")
> files <- paste(paste(getwd(),lfile,sep="/"), list.files(lfile),sep="/")# getwd of these files
>
> dput(lfile)
> c("rcp45_Daily_Sim001.dat", "rcp45_Daily_Sim002.dat")
>
>
> - How can I rename these files (200 in number) using something like:
> file.rename(lfile, paste0("rcp45_Daily_Sim", 1:200))?The new filenames should be rcp45_Daily_Sim001, rcp45_Daily_Sim002, ..., rcp45_Daily_Sim200.
>
> - I would like to write the new file names to the directory.
>
> The data files contain huge amounts of data and should not be read into R. Only the file names should change.
>
> Many thanks for your helpful answers.
> Asong.
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list