I want to iterate over different file names. The file names are XY1.txt, XY2.txt…XY500.txt. Each file that is taken as input generates 3 output files which I want to rename according to the current index. For XY1.txt, output1.txt becomes 1_1.txt, output2.txt becomes 1_2.txt and so on. But I do not know how to change the filename as per index. I looked it up but I was not finding what I needed on this website or elsewhere. I am new to bash. The below pseudo code is what I was able to write until now. Please help me out
for i in {1..500} ;
filename = "XY"+str(i) + ".txt" ;
do ./CompiledCodeFile -filename -use_option 4;
mv output1.txt str(i)+"_1.txt" ;
mv output2.txt str(i)+"_2.txt" ;
mv output3.txt str(i)+"_3.txt" ;
done
>Solution :
edit: corrected a little error in the code.
#!/bin/bash
for i in {1..500}
do
filename="XY$i.txt"
./CompiledCodeFile "$filename" -use_option 4
mv output1.txt "${i}_1.txt"
mv output2.txt "${i}_2.txt"
mv output3.txt "${i}_3.txt"
done
notes:
$i
and${i}
, what’s the difference?
They’re the same thing, but sometimes you need to use the ${}
for differentiating the variable name from the following letters (here the _
)
- Why use double quotes for expanding variables, for example
"$filename"
?
That’s mandatory