Greg T.D.
Greg T.D.

Reputation: 49

Rename files with loop variable name

I am trying to download a bunch of files and rename them as I go. the download portion works correctly, but i can't get it to rename the files. This is the script I'm using:

COUNTER=0
for (( i = 696; i <= 773; i++ ))
  do
  fastq-dump --split-3 --accession SRR546$i
mv SRR546"$i"_1 ./"$COUNTER"mVD_SRR546$i_1
mv SRR546"$i"_2 ./"$COUNTER"mVD_SRR546$i_2
gzip *.fastq

COUNTER=$[COUNTER + 1]
done

This will correctly download the file SRR546696, SRR546697 etc. but does nothing to rename them.

I also tried using:

rename 's/SRR/"$COUNTER"mVD_SRR/' *.fastq

but this also did nothing.

Upvotes: 2

Views: 872

Answers (2)

Ulises Rosas-Puchuri
Ulises Rosas-Puchuri

Reputation: 1970

When you combine a variable name with a string, only string should be quoted:

COUNTER=0
for (( i = 696; i <= 773; i++ )); do

    fastq-dump --split-3 --accession 'SRR546'$i

    mv 'SRR546'$i'_1' ./$COUNTER'mVD_SRR546'$i'_1'
    mv 'SRR546'$i'_2' ./$COUNTER'mVD_SRR546'$i'_2'
    gzip *.fastq

    COUNTER=$[COUNTER + 1]
done

Upvotes: 0

codeforester
codeforester

Reputation: 42999

You need to double quote the arguments to prevent word splitting and globbing. At the same time, you need to preserve the variable names with {}:

counter=0
for ((i = 696; i <= 773; i++)); do
  fastq-dump --split-3 --accession "SRR546$i"
  mv "SRR546${i}_1" "./${counter}mVD_SRR546${i}_1"
  mv "SRR546${i}_2" "./${counter}mVD_SRR546${i}_2"
  gzip *.fastq
  ((counter++))
done

Instead of hardcoding "SRR546" in so many places, you could use a variable to hold that string and make your code more readable:

counter=0 srr="SRR546"
for ((i = 696; i <= 773; i++)); do
  fastq-dump --split-3 --accession "$srr$i"
  mv "$srr${i}_1" "./${counter}mVD_${srr}${i}_1"
  mv "$srr${i}_2" "./${counter}mVD_${srr}${i}_2"
  gzip *.fastq
  ((counter++))
done

Improvements:

  • use lower case for your normal variables (counter instead of COUNTER)
  • use quoting to prevent word splitting and globbing (though not an issue in your problem since the variable holds a number, free from space or other meta characters
  • use a single set of double quotes rather than multiple single quotes
  • use ++ operator to increment counter as in ((counter++) and ((...)) is a better syntax than $[ ... ]

You may want to add error checking to your code.

Related

Upvotes: 5

Related Questions