0

I wanna loop through the array and print out each element in a bash script:

array=(10, 0.2, 0.03,)
for ele in ${array[@]}
do
echo "$ele blah" 
done

However, it spits out:

10, blah
 blah
0.2, blah
 blah
0.03 blah

Even if I added

IFS=","

The result is :

10 blah
 blah
0.2 blah
 blah
0.03 blah

How can I get:

10 blah
0.2 blah
0.03 blah

After this, I would like to align each line like:

10.00      blah
0.200      blah
0.030      blah

Updated:

With the 1st and 2nd column separated by 6 spaces

Is there any easy way to do this? Thanks.

1
  • @jenesaisquoi this will cause 10 to stretch out by one compared to 0.2 and 0.03 Commented Jan 25, 2017 at 1:53

2 Answers 2

3

Remove the commas in your array declaration.

array=(10 0.2 0.03)

You also may want to double your expansion in the for loop, unless you are 100% sure there is no chance that word splitting will cause problems (note that in the case of your sample data it won't).

for ele in "${array[@]}"

To format the output, try (instead of echo)

printf "%06.3f      blah\n" "$ele"

You need to increase the number following the % sign if you need more digits before the decimal separator, and you remove the 0 to avoid printing leading zeros if you do not want them. For instance :

printf "%10.3f      blah\n" "$ele"
Sign up to request clarification or add additional context in comments.

1 Comment

I added an explanation for that at the end of my answer.
0

You can remove the commas doing:

for ele in `echo ${array[@]} | sed 's/,//g'`;

Instead of

for ele in ${array[@]}

sed is a very useful tool for doing small manipulations in texts such as replacements with the "s" function. Definitely worth playing around with :)

For the alignment you can use tabs instead of space and printf instead of echo. So use:

printf "%-10.3fblah\n" $ele

instead of

echo "$ele blah"

2 Comments

Do you think the OP needs to use a separate command to remove commas instead of simply not using them in the first place?
this will cause 10 to stretch out by one compared to 0.2 and 0.03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.