Skip to content
Prev 349869 / 398525 Next

recursively rename dir and files

hi jim

thank you very much for your help: what a nice piece of code!

inspired by your neat solution let me here post a slight variation upon
your lines which is now also dealing also with caps in file and dir names
(a potentially useful function for the proper "housekeeping" of the wd)

it works but there is one potentially "dangerous" drawback (to be somehow
controlled): it renames the R code file eventually present in the wd which
is usually named something like *.R which is renamed as *.r

I definitely need to think a viable solution to avoid that problem...

####

setwd(".")
dir.create("./My Dir with Spaces and Caps")
dir.create("./My Dir with Spaces and Caps/My Sub Dir With Spaces and Caps")
file.create("./My Dir with Spaces and Caps/My Dir file With Spaces and
Caps.txt")
file.create("./My Dir with Spaces and Caps/My Sub Dir With Spaces and
Caps/My Sub Dir File With Spaces and Caps.txt")
file.create("./My Dir with Spaces and Caps/My Sub Dir With Spaces and
Caps/MySubDirFileJustWithCaps.txt")

#new function
recursive_replace_lowercase<-function(path=".", replace=" ", with="_",
lowercase=TRUE) {

  # this is the base case

  filelist<-list.files(path, full.names=TRUE)

  if (lowercase) {

    for(filename in filelist)
      file.rename(filename,gsub(replace,with,tolower(filename)))

  } else {

    for(filename in filelist)
      file.rename(filename,gsub(replace,with,filename))
  }

  # and this is the recursive part

  dirlist<-list.dirs(path, full.names=TRUE, recursive=FALSE)

  if(length(dirlist)) {

    for(dirname in dirlist)
      recursive_replace_lowercase(dirname, replace=replace, with=with,
lowercase=lowercase)
  }
}

recursive_replace_lowercase()