1

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.

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

9 Comments

thanks for quick response. I actually don't have an input file I'm getting those lines from the sed output, how can I feed the input lines one at a time to this above code ?
Just remove the < "$1".
I think, I'm doing something wrong if I just use the input file do I have to pass the path somewhere in the above code ? as I see this stack-answer.sh: 3: stack-answer.sh: cannot open : No such file
and If I add the file name in place of "$1" I get stack-answer.sh: 3: read: Illegal option -a
How do you run the script?
|

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.