[R] recursively rename dir and files

John McKown john.archie.mckown at gmail.com
Fri Apr 10 15:49:59 CEST 2015

On Thu, Apr 9, 2015 at 2:58 PM, 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
​You need to rename each file in each subdirectory. But you must first
split the file name from the directory name. You then rename the file,
keeping the directory name the same. In order for this to work, you must
first rename all files in a given directory _before_ attempting to rename
the directory. Once each file in a directory is renamed, then you can try
to rename the directory itself. I.e. you must process the files in "depth"
order. The following code does that.

filesAndDirs=dir(".", full.names=TRUE, recursive=TRUE, include.dirs=TRUE)
hasBlanks=filesAndDirs[grepl(" ",filesAndDirs)] #only things with blanks,
for(file in sortedBlankList) {
    newBack=gsub(" ","_",back)
    if(newBack != back) {
​ #actually need to do a rename​

​BTW - neat turban. Is it Sikh? Hope you don't mind my curiosity.​

If you sent twitter messages while exploring, are you on a textpedition?

He's about as useful as a wax frying pan.

10 to the 12th power microphones = 1 Megaphone

Maranatha! <><
John McKown

	[[alternative HTML version deleted]]

More information about the R-help mailing list