Search code examples
bashawkmv

How to move files to different folders based on their prefix?


  • I have thousands of files in my home folder that look like this:
> ls 

6_2_S28_R1_001.fastq.gz  
19_1_S160_R1_001.fastq.gz
25_3_S114_R1_001.fastq.gz
  • Here, as an example, I break down the name of the file 6_2_S28_R1_001.fastq.gz;
    6_ = day6
    2_ = replicate 2
    S28_R1_001.fastq.gz = extension

  • In the same directory I have the folders

rep1
rep2
rep3

My goal

I am trying to move each file to a different folder based on the prefix, that is related to the replicate

6_2_S28_R1_001.fastq.gz,   #this file needs to be moved to rep2 <br>
19_1_S160_R1_001.fastq.gz, #this file needs to be moved to rep1 <br>
25_3_S114_R1_001.fastq.gz, #thus file needs to go to rep3 folder <br>

I have tried an unsuccessful for loop. Any help or guidance are appreciated


Solution

  • #! /bin/bash
    for f in *_*_*_*_*.gz; do
        i="${f#*_}"; i="${i%%_*}"
        d="rep$i"
        echo "Move '$f' to '$d'"
        mkdir -p "$d" \
        && mv "$f" "$d"
    done