TransWikia.com

How can i move multiple files to folder with same name

Ask Ubuntu Asked by tucanco on January 3, 2021

I have multiple files like this:

round3-bcF_01_bcR_01.R1.fastq
round3-bcF_01_bcR_01.R2.fastq
round4-bcF_01_bcR_01.R1.fastq
round4-bcF_01_bcR_01.R2.fastq
round3-bcF_01_bcR_02.R1.fastq
round3-bcF_01_bcR_02.R2.fastq
round4-bcF_01_bcR_02.R1.fastq
round4-bcF_01_bcR_02.R2.fastq

and goes on until this form:

round3-bcF_12_bcR_08.R1.fastq
round3-bcF_12_bcR_08.R2.fastq

Also, I have different folders like these ones:

bcF_01_bcR_01
bcF_01_bcR_02
bcF_01_bcR_03 

etc… until

bcF_12_bcR_08

I’m moving the files with this line:

mv *-bcF_01_bcR_01* bcF_01_bcR_01 

Therefore, 4 files should be left in each folder, but its taking me forever because I have to run 96 times the code ( I have more replicas so I have more than 96 folders).

All I want is to move files with this part of the name "bcF_01_bcR_01" to folders of the same name. Im new with bash so any help is appreciated. Thank you

3 Answers

In this particular case, probably the most simple way is to use the builtin for loop in a way as this:

for i in {01..08}; do echo mv *-bcF_01_bcR_${i}* bcF_01_bcR_${i}/; done 
  • remove the echo command in order to do the actual file-system changes.

Correct answer by pa4080 on January 3, 2021

mmv (from the package of the same name) is useful for cases like this:

$ mmv -n '*-bcF_01_bcR_*.*' 'bcF_01_bcR_#2/'
round3-bcF_01_bcR_01.R1.fastq -> bcF_01_bcR_01/round3-bcF_01_bcR_01.R1.fastq
round3-bcF_01_bcR_01.R2.fastq -> bcF_01_bcR_01/round3-bcF_01_bcR_01.R2.fastq
round3-bcF_01_bcR_02.R1.fastq -> bcF_01_bcR_02/round3-bcF_01_bcR_02.R1.fastq
round3-bcF_01_bcR_02.R2.fastq -> bcF_01_bcR_02/round3-bcF_01_bcR_02.R2.fastq
round4-bcF_01_bcR_01.R1.fastq -> bcF_01_bcR_01/round4-bcF_01_bcR_01.R1.fastq
round4-bcF_01_bcR_01.R2.fastq -> bcF_01_bcR_01/round4-bcF_01_bcR_01.R2.fastq
round4-bcF_01_bcR_02.R1.fastq -> bcF_01_bcR_02/round4-bcF_01_bcR_02.R1.fastq
round4-bcF_01_bcR_02.R2.fastq -> bcF_01_bcR_02/round4-bcF_01_bcR_02.R2.fastq

Here, #2 refers to the second wildcard match in the expression *-bcF_01_bcR_*.* - you can easily extend it to do multiple replacements in a single shot e.g.

mmv -n '*-bcF_*_bcR_*.*' 'bcF_#2_bcR_#3/'

Remove the -n to actually make the moves. If you use zsh, it has a loadable equivalent zmv.

Answered by steeldriver on January 3, 2021

Using rename to move files:

$ rename -n 's/.*(bcF_[0-9]+_bcR_[0-9]+).*/$1/$&/' *.fastq

Remove -n when you feel ready to move your files.

Answered by bac0n on January 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP