Bash array from file

So I'm having a text file called myfile that looks like:

epochdate1 floatvalue1
epochdate2 floatvalue2
...
epochdaten floatvaluen

I was thinking to create an array where I can extract some floatvalues: floatvaluen, floatvalue(n-1), floatvalue(n-100).

How to achieve that? I mean how to declare this array from myfile and how to select the elements?

1 answer

  • answered 2018-01-14 15:27 iBug

    You can create an array in Bash like this:

    myarr=($(awk '{print $2}' file.txt))
    

    And you'll be able to access its elements like

    echo ${myarr[0]}
    echo ${myarr[10]}
    

    Or better yet, declare an associative array:

    declare -A myarr
    eval myarr=($(awk '{print "["$1"]="$2}' file.txt))
    

    And you'll be able to access it like

    echo "${myarr[epochdaten]}"
    

    Output: floatvaluen