My bamFiles are currently "11.bam" "114.bam" "132.bam" "60.bam". I want to add chr16_ to the front of each file. These names should be back into the bamFiles character vector.
Code:
bamPath = "C:/Users/User/Downloads/chr16_bam"
for(f in bamPath){file.rename(list.files(pattern=".bam$", all.files=F, full.names=F), paste("chr16", sep="_", f))}
Traceback:
Error in file.rename(list.files(pattern = ".bam$", all.files = F, full.names = F), :
'from' and 'to' are of different lengths
Expected output:
"chr16_11.bam" "chr16_114.bam" "chr16_132.bam" "chr16_60.bam"
CodePudding user response:
Try This Solution, It's working perfectly at my end, now its your turn
> library(reproducible)
> bamPath = "C:/Users/User/Downloads/chr16_bam"
> files <- list.files(bampath ,pattern = "*.bam",full.names = T)
> sapply(files,FUN=function(eachPath){
file.rename(from=eachPath,to= .prefix(eachPath, "chr16_"))
})
Console Logs Should be like this
C:/Documents/Sample/16_161.bam
TRUE
C:/Documents/Sample/16_162.bam
TRUE
C:/Documents/Sample/16_163.bam
TRUE
If your getting
"TRUE"
then its renamed successfully also check folder where your files kept
Thanks....!
CodePudding user response:
Maybe I am not getting something here. If your issue is just to rename a bunch of files, this should do the trick.
I added to my home folder exactly the files you mentioned: 11.bam
, 114.bam
, 132.bam
, 60.bam
.
> oldfiles = list.files("~/", pattern = "*.bam")
> oldfiles
# [1] "11.bam" "114.bam" "32.bam" "60.bam"
>
> newfiles = paste0("chr16_", oldfiles)
> newfiles
# [1] "chr16_11.bam" "chr16_114.bam" "chr16_32.bam" "chr16_60.bam"
>
> file.rename(oldfiles, newfiles)
# [1] TRUE TRUE TRUE TRUE
>
> list.files("~/", pattern = "*.bam")
# [1] "chr16_11.bam" "chr16_114.bam" "chr16_32.bam" "chr16_60.bam"