# # (gH) -_- renomme.r ; TimeStamp (unix) : 22 Avril 2016 vers 18:12 ################################################################################# # # this script renames all files corresponding to the variable before # by replacing before with the contents of the variable after. # # for instance with before = "_001.fastq" and after = ".fastq" # the files Aba1_S1_L001_R1_001.fastq, Xa1_S2_L001_R1_001.fastq... # will be renamed Aba1_S1_L001_R1.fastq, Xa1_S2_L001_R1.fastq # ################################################################################# args <- commandArgs(trailingOnly=TRUE) nbArgs <- length(args) if (nbArgs==0) { cat( "\n" ) ; cat( " the script renomme.r renames all files corresponding to the substring BEFORE \n") ; cat( " by replacing BEFORE with AFTER\n\n") ; cat( "syntax : Rscript --vanilla renomme.r BEFORE AFTER \n") ; cat( "examples : Rscript --vanilla renomme.r _OO1.fastq .fastq \n") ; cat( " Rscript --vanilla renomme.r _XX1.fastq R1.fastq \n") ; cat( "\n\n" ) ; stop(-1) ; } ; # end if if (nbArgs==1) { cat("Argument 2 is missing.\n") ; cat("Syntax is : Rscript --vanilla renomme.r BEFORE AFTER \n") ; stop(-2) ; } ; # end if before <- args[1] after <- args[2] files <- dir(path=".",pattern=paste("*",before,"*",sep="")) ; nbf <- length(files) # warn if no file corresponds to the specification if (nbf==0) { cat("\nAlas, no files corresponds to the specification \"",before,"\". Nothing to do !\n\n",sep="") ; } else { msg <- paste("Renaming ",nbf," file(s) corresponding to the specification \"",before,"\".",sep="") ; sou <- paste(rep(x="=",times=nchar(msg)),collapse="") ; cat("\n",msg,"\n",sou,"\n\n",sep="") ; } ; # end if for (file in sort(files)) { newFile <- gsub(x=file,pattern=before,replacement=after) if (newFile!=file) { if (file.exists(newFile)) { cat("File ",newFile," already exists, file ,",file," will not be renamed.\n",sep="") ; } else { if (file.rename(file,newFile)) { cat("File ",file," has been renamed ",newFile,"\n",sep="") ; } else { cat("Cannot rename file ",file," as ",newFile,"\n",sep="") ; } # end if } # end if } # end if } ; # end of foreach # end of script