AFAIK this is bash-specific.

Imagine we have a variable set in a script like…

variable="string1,string2,string3,string4"

We can loop through these comma separated values like this…

for loop in ${variable//,/ }
do
   echo $loop
done

And we would see…

string1
string2
string3
string4

We can extend this example for key pairs. Let’s use : to separate the pairs…

variable="apples:2,oranges:5,bananas:23,pineapples:7"

To just get the value for oranges we can search with a similar loop…

for loop in ${variable//,/ }
do
   fruit=$(echo $loop | awk -F: '{print $1}'
   [[ "$fruit" == "oranges" ]] && echo $loop | awk -F: '{print $2}'
done

Probably a cleverer way, but I like it.

About troyski

I'm a freelance UNIX engineer working in the UK. I'm married to Tina and between us we have six children. I'm a bit of an Apple fan boy, and all the Windows machines in the house are a thing of the past now.

Comments are closed.

Private

Post navigation