[R] recursively rename dir and files
Jim Lemon
drjimlemon at gmail.com
Fri Apr 10 01:44:29 CEST 2015
Hi maxbre,
Try this:
recursive_replace<-function(path=".",replace=" ",with="_") {
filelist<-list.files(path,full.names=TRUE)
for(filename in filelist) {
if(length(grep(replace,filename)))
file.rename(filename,gsub(replace,with,filename))
}
dirlist<-list.dirs(path,full.names=TRUE,recursive=FALSE)
if(length(dirlist)) {
for(dirname in dirlist)
recursive_replace(dirname,replace=replace,with=with)
}
}
Jim
On Fri, Apr 10, 2015 at 5:58 AM, maxbre <mbressan at arpa.veneto.it> wrote:
> this is my reproducible example
>
> setwd(".")
> dir.create("./my dir with space")
> dir.create("./my dir with space/my sub dir with space")
> file.create("./my dir with space/my dir file with space.txt")
> file.create("./my dir with space/my sub dir with space/my sub dir file with
> space.txt")
>
> now I need to rename recursively all dirs and files in order to get rid of
> spaces
>
> the following attempt is not getting to the point...
>
> mylist<-dir(".", full.names=TRUE, recursive=TRUE, include.dirs=TRUE)
>
> for (i in mylist){
> file.rename(i, gsub(" ", "_", i))
> }
>
> #or more simply...
> file.rename(mydirs, gsub(" ", "_", mydirs))
>
> ...because (clearly) I got some warning messages like "can not rename file
> .... because it is not existing";
> and I definitely understand that because in the process of renaming of the
> the upper level directory the full path of the nested directories and files
> is changed and any longer visible to the procedure...
>
> the problem now is that I'm not enough clear how to proceed with an
> alternative strategy in order to properly sort out the problem...
>
> for reasons I'm not mentioning here I must stick with a solution in R
> language
>
> any hint much appreciated
>
> thanks
>
>
>
>
>
>
> --
> View this message in context:
> http://r.789695.n4.nabble.com/recursively-rename-dir-and-files-tp4705667.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list