rshdzrt
rshdzrt

Reputation: 135

Nested for-loop and arrays in Bash

I have an input file which is comma separated lines, which I need to assign to the keys as mentioned below, I have tried assigning them but I'm not able to figure out how to assign them separately yet group together as shown below expected result.

I would really appreciate if someone can help me with this, I have not used the arrays or comma separated values before and having issue to get it to work.

Input file

10.219.196.0,15gb,Azure Cloud
10.219.196.0,55gb,Google Cloud
10.219.196.0,54gb,AWS Cloud

I have to assign the IP address with key IP, size with key size and the cloud name with key platform, the tricky part is I have to assign it this way

Expected Result

IP1=10.219.196.0
Size1=15gb
Platform1=Azure Cloud
IP2=10.219.196.0
Size2=15gb
Platform2=Google Cloud
IP3=10.219.196.0
Size3=15gb
Platform3=AWS Cloud

Solution I have tried is as below

i=1;
for $line in `cat file`
 do 
    my_ary=$line
    echo "IP$i=${my_ary[0]}"\n
    echo "Size$i=${my_ary[1]}"\n
    echo "platform$i=${my_ary[2]}"\n
    $i++
 done

Please let me know how can I fix this to get the expected result.

Upvotes: 1

Views: 202

Answers (1)

choroba
choroba

Reputation: 241758

The variable in for must be used without the dollar sign.

Instead of looping over cat, you can read the file directly into the array using read -a. Setting $IFS splits each line on commas.

For increment, use an arithmetic expression ((...)).

echo adds a newline after printing its arguments. No need to write \n.

#! /bin/bash
i=1
while IFS=, read -a my_ary ; do 
    echo "IP$i=${my_ary[0]}"
    echo "Size$i=${my_ary[1]}"
    echo "Platform$i=${my_ary[2]}"
    ((i++))
done < "$1"

Upvotes: 1

Related Questions