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

Time:12-17

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>

CodePudding user response:

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>

CodePudding user response:

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>
  •  Tags:  
  • bash
  • Related