Search code examples
arraysbashifs

Bash multiarray and IFS


I have a problem in my bash script.

I would split a string into an (indexed named) array:

The string can have this values: status=online clients=5 name=Server the string can also have several commands have like these (that's the problematic): status=online clients=5 name=Server|status=offline clients=0 name=Server_2

First Question: How can i split, or should i check, if this "|" exists?

Second Question: I must split now this values into an named array like from string: status=online clients=5 name=Server and the array looks like:

[status] = [online]
[clients] = [5]
[name] = [Server]

And if the separator "|" exists, i must get the results in 2 (or more) arrays:

$mainarray [0]
[status] = [online]
[clients] = [5]
[name] = [Server]

$mainarray [1]
[status] = [offline]
[clients] = [0]
[name] = [Server2]

And for example, with echo $mainarray[0][status] i would get "online".

Is it possible to do that?


Solution

  • You can use pseudo-multidimensional associative arrays.

    str='status=online clients=5 name=Server|status=offline clients=0 name=Server_2'
    n=0
    declare -A ary
    
    # split the string on "|"
    IFS='|' read -ra sets <<< "$str"
    
    # interate over the sets of variables to populate the array
    for set in "${sets[@]}"; do
        IFS=' ' read -ra pairs <<< "$set"
        for pair in "${pairs[@]}"; do
            IFS='=' read var value <<< "$pair"
            ary["$n,$var"]=$value
        done
        ((n++))
    done
    
    # now, what do we have?
    for key in "${!ary[@]}"; do 
        printf "%s => %s\n" "$key" "${ary["$key"]}"
    done
    

    The order of the output is undetermined

    0,clients => 5
    1,status => offline
    1,name => Server_2
    0,status => online
    1,clients => 0
    0,name => Server