Problem renaming files using variables

Hi, I have the following problem:

I have a list of files:

1.txt
2.txt
3.txt
4.txt

Then I have a list of variable names inside variable.txt:

A
B
C
D

I'd like to rename 1.txt, 2.txt etc using the variables from variable.txt

 
A.txt (Contains info from 1.txt)
B.txt (Contains info from 2.txt)
C.txt (Contains info from 3.txt)
D.txt (Contains info from 4.txt)

I've tried using this, but it doesn't work

END=4
for ((i=1;i<=END;i++)); do for j in $(cat variable.txt); do mv "$i".txt "$j".txt; done; done

When doing this, I get a list of files

 
A.txt  > (Contains info from 4.txt)
B.txt  > (Contains info from 4.txt)
C.txt  > (Contains info from 4.txt)
D.txt  > (Contains info from 4.txt)

but want

A.txt (Contains info from 1.txt)
B.txt (Contains info from 2.txt)
C.txt (Contains info from 3.txt)
D.txt (Contains info from 4.txt)

Something is going wrong with the loop and can't work out why it's doing this. I'm trying to learn scripting/loops and any help would be appreciated. Many thanks

Hi, the error is the nested loops: try this way

END=4
for ((i=1;i<=END;i++))
do 
N=`sed -n ${i}p variable.txt`
mv ${i}.txt ${N}.txt
done
1 Like

That's fantastic franzpizzo, does exactly what I wanted. Thanks very much for your help :slight_smile: