Emalek
Emalek

Reputation: 25

Rename files by matching key value from a text file bash

I have files in directories like:

./PBMCs/SRR1_1.fastq
./PBMCs/SRR1_2.fastq
./Monos/SRR2.fastq
./Monos/SRR3.fastq

I want to change the SRR# to a more informative name based on a file of key-value pairs:

SRR1 pbmc-1
SRR2 mono-1
SRR3 mono-2

And rename the files as:

./PBMCs/pbmc-1_1.fastq
./PBMCs/pbmc-1_2.fastq
./Monos/mono-1.fastq
./Monos/mono-2.fastq

All that I can think to do is loop through the list of original files and then loop through the lines of the name-change.txt file and replace the strings. However, I'm not sure how to implement this or if it's a good way to approach this.

Upvotes: 0

Views: 210

Answers (1)

oguz ismail
oguz ismail

Reputation: 50750

Assuming all *.fastq are one subdirectory deep, this should work fine:

while read old new; do
  for fastq in ./*/"$old"*.fastq; do
    new_name=$new${fastq##*/"$old"}
    echo mv "$fastq" "${fastq%/*}/$new_name"
  done
done <name-change.txt

Remove echo if the output looks good.

Upvotes: 1

Related Questions