Sergiu
Sergiu

Reputation: 3185

Bash key value pair

I am doing a bash scripts which reads in a csv file similar to:

Name, Surname, Course
X,    Y,       Maths,
A,    B,       Science,
C,    D,       Maths,
E,    F,       Science,
G,    H,       Science,

And I have tried to implement something like:

declare -a newmap
newmap[name]="${myarray[0]}"
newmap[course]="${myarray[3]}"

echo "Name ${newmap[name]}"
echo "Course ${newmap[course]}" 

But I am not sure, how to use it while reading the file.

Thank you

Upvotes: 0

Views: 405

Answers (1)

Rajeev Ranjan
Rajeev Ranjan

Reputation: 4076

Try using the following if all you want is print to the console -

while read -r line;
do 
    IFS=',' read -ra myarray <<< $line

    [ "${myarray[0]}" == "Name" ] && continue

    echo "Name ${myarray[0]}"
    echo "Course ${myarray[2]}"
done < "${1:-/dev/stdin}"

This would read from your input file (change from console as used here). It then tokenizes each line by , to get the fields.

Upvotes: 0

Related Questions