Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Move files with a certain pattern to a certain folder in bash

I have thousands of files that look like this:

6_2_S28_R1_001.fastq.gz
19_1_S160_R1_001.fastq.gz
25_3_S114_R1_001.fastq.gz

in the same directory I have the folders

rep1
rep2
rep3

I am trying to move each file to a different folder based on the prefix, second number:
6_2_S28_R1_001.fastq.gz, this file needs to be moved to rep2
19_1_S160_R1_001.fastq.gz, this file needs to be moved to rep1
25_3_S114_R1_001.fastq.gz, thus file needs to go to rep3 folder

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading