0

I have a Bash script where i have calculated many values and stored them in the variables which have a number for each row. For instance, i have a variable named as TC_5 which calculates the value of 5th row of the input csv file. I have calculated all the values and stored in variables which have the naming convention of TC_<Row_No> so that for 200 rows i have values stored in:

TC_1
TC_2
.
.
TC_200

Now, i want to write a loop which could print the values of all these variables together to an external file instead of manually printing them. For this, i am using the while loop as follows:

i=0
while [ "$i" != 201 ]
do
    echo "TC_$i" >> Out
    i=`expr $i + 1`
done

How can i modify the above code in such a way that the echo statement would print the variable TC_<RowNo> to the Out File?

  • Why not use awk/sed? – MatthewRock Sep 22 '15 at 8:03
  • Do you hear about arrays? – Costas Sep 22 '15 at 8:25
  • Hello Guys, could you please provide your suggestions as answers? I don't want to do it strictly with while loop. Any other option which is faster and better would be appreciated. Of course i have heard about arrays :) – Ankit Vashistha Sep 22 '15 at 9:29
2

Your current script stuck in an infinitive loop, because the condition [ "$i" != 201 ] was always true.

You must increase $i after each iteration and using eval to print the content of TC_<RowNo> variable (but it's not safe):

i=1
while [ "$i" -ne 201 ]
do
    eval printf '%s\\n' "\${TC_$i}"
    i=$((i+1))
done >> "Out"

Note that $i started at 1, the use of -ne for integer comparison and the redirection at the end of while loop.

  • Good point cuonglm. Actually i missed to put the increment statement in the above example. That is present in my main script. Thanks for your answer. I will try it and get back to you. – Ankit Vashistha Sep 22 '15 at 9:06

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.