GJO2
GJO2

Reputation: 25

How to iterate both on alphabet and integer in a bash loop

My code

for ((i={A..Z}, j=30 ; i < $words2 + 1, j < (30 + (20 * $words2)) ; i++, j+=20)) ; 
do
  printf '%s %s %s\n' '<text x="'$j'" y="10">'$i'</text>' | sed 's/ *$//' 
done

and the output that I get is

<text x="30" y="10">0</text>
<text x="50" y="10">1</text>
<text x="70" y="10">2</text>
<text x="90" y="10">3</text>

I would like to go over the alphabet until i is less than $words2 but i apparently stays a letter. My desired output is this where i is equal to the alphabet in uppercase

<text x="30" y="10">A</text>
<text x="50" y="10">B</text>
<text x="70" y="10">C</text>
<text x="90" y="10">D</text>

Upvotes: 0

Views: 40

Answers (2)

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185219

Like this:

arr=( {A..Z} )
for ((i=0, j=30; i<=4, j<=70; i++, j+=20)); do
    printf '<text x="%d" y="10">%s</text>\n' $j "${arr[i]}"
done 

Output

<text x="30" y="10">A</text>
<text x="50" y="10">B</text>
<text x="70" y="10">C</text>

Upvotes: 3

M. Nejat Aydin
M. Nejat Aydin

Reputation: 10123

I'd do it like this:

#!/bin/bash

words2=4
i=0
for upper in {A..Z}; do
    ((++i > words2)) && break
    printf '<text x="%d" y="10">%s</text>\n' $((10+i*20)) "$upper"
done

This prints out

<text x="30" y="10">A</text>
<text x="50" y="10">B</text>
<text x="70" y="10">C</text>
<text x="90" y="10">D</text>

Upvotes: 1

Related Questions