Array in Shell

Hi, I have following issue while using Array in Shell script

I have input file as below

FILE1=filename1,filelocation1
FILE2=filename2,filelocation2
FILE3=filename3,filelocation3
FILE4=filename4,filelocation4
FILE5=filename5,filelocation5
FILE6=filename6,filelocation6

I want traverse these file and get both filename and filelocation in different variables.

Can you please help me?

This is straight forward and should work in both Kshell and bash. After the loop executes two arrays (indexed 0 to n-1) will exist:

i=0
sed 's/.*=//; s/,/ /' your-file  >/tmp/tfile.$$
while read a b
do
    names[$i]="$a"
    locs[$i]="$b"
    (( i++ ))
done </tmp/tfile.$$
rm /tmp/tfile.$$

The code above can be done in Kshell without using a tmp file; pipe the output from the sed directly into the while. Unfortunately that won't work in bash which is why I presented it the way I did.

This code below is more cryptic, but doesn't require the use of a tmp file to work in bash:

eval $(awk -F "[=,]" '
    {
        names = names " " $2;
        locs = locs " " $3;
    }
    END { printf( "names=( %s ); locs=( %s )", names, locs ); }
' your-input-file )
1 Like

And slightly tweaking agama's solution, here's without the use of temp file.

#! /bin/bash

i=0
while IFS=, read a b
do
    names[$i]=${a#*=}
    locs[$i]=$b
    (( i++ ))
done < inputfile
3 Likes

Thanks Agama and Balajesuri for your responses...