## Code in public domain ## If you have questions about how to use this code, ## or if you want to suggest improvement, feel free to email me to ## francois.michonneau@gmail.com ## 'add.zeros' adds zeros to match a given length ## for instance add.zeros(4, 3) returns '004'. add.zeros <- function(x, final.length) { zeros.to.add <- character(0) nb.zeros <- final.length - nchar(x) if(nb.zeros < 0) { stop("Final length must be positive") } else { if(nb.zeros == 0) { return(x) } else { for(i in 1:nb.zeros) { zeros.to.add <- paste(zeros.to.add, "0", sep="") } zeros.added <- paste(zeros.to.add, x, sep="") return(zeros.added) } } } ## 'rename.jpg.nef' renames photo files in working directory with a 'prefix' ## and a number. The series of number is initiated by the value of counter. ## this function requires the function 'add.zeros'. ## If both JPG and NEF files are present, they are given the same numbers. ## User is prompted before files are renamed. rename.jpg.nef <- function(prefix = character(0), counter = 1, pattern = "DSC_", length.nb = 4) { i.each.file <- 1 ## Get list of files list.img <- list.files(pattern = pattern) old.names <- new.names <- character(length(list.img)) ## Get file names without the extension uniq.names <- unique(sapply(list.img, function(x) unlist(strsplit(x, "\\."))[1])) for(each.file in uniq.names) { counter.with.z <- add.zeros(counter, length.nb) ## If JPG old.jpg <- paste(each.file, "JPG", sep=".") if(file.exists(old.jpg)) { new.jpg <- paste(prefix, counter.with.z, ".JPG", sep="") old.names[i.each.file] <- old.jpg new.names[i.each.file] <- new.jpg i.each.file <- i.each.file + 1 } ## If NEF old.nef <- paste(each.file, "NEF", sep=".") if(file.exists(old.nef)) { new.nef <- paste(prefix, counter.with.z, ".NEF", sep="") old.names[i.each.file] <- old.nef new.names[i.each.file] <- new.nef i.each.file <- i.each.file + 1 } counter <- counter + 1 } df.rename <- cbind(old.names, new.names) if(nrow(df.rename) == 0) stop("Nothing to rename") print(df.rename) ## Check if files already exist sapply(new.names, function(foo) if(file.exists(foo)) stop(foo," already exists, check counter")) ## Rename files prt <- readline("Proceed (yes/no)? \n") if(prt == "yes" || prt == "y") apply(df.rename, 1, function(x) file.rename(x[1], x[2])) else cat("stopped by user \n") }