Search code examples
bashshellfor-loopunixecho

How to iterate over multiple variables and echo them using Shell Script?


Consider the below variables which are dynamic and might change each time. Sometimes there might even be 5 variables, But the length of all the variables will be the same every time.

var1='a b c d e... upto z'
var2='1 2 3 4 5... upto 26'
var3='I II III IV V... upto XXVI'

I am looking for a generalized approach to iterate the variables in a for loop & My desired output should be like below.

a,1,I
b,2,II
c,3,III
d,4,IV
e,5,V
.
.
goes on upto
z,26,XXVI

If I use nested loops, then I get all possible combinations which is not the expected outcome.

Also, I know how to make this work for 2 variables using for loop and shift using below link https://unix.stackexchange.com/questions/390283/how-to-iterate-two-variables-in-a-sh-script


Solution

  • With paste

    paste -d , <(tr ' ' '\n' <<<"$var1") <(tr ' ' '\n' <<<"$var2") <(tr ' ' '\n' <<<"$var3")
    
    a,1,I
    b,2,II
    c,3,III
    d,4,IV
    e...z,5...26,V...XXVI
    

    But clearly having to add other parameter substitutions for more varN's is not scalable.