Bash – How to split the output and store it in an array

bash

This is the output:

3,aac-lc, 93.8, aaclc, 77.3, h.264, 1024.6, h.264, 1029.1, 31, 31, 0,0,0.000000,31,31,0,0,0.000000,7,0,0,0.000000,30,1280 720,10,0,0,0.000000,30,1280 720

I tried with 2 scenario:

  1. Storing in an array

      @arr=split(',',$stats);
      echo "statistics: $stats"
    
  2. Storing in a variable

     echo $stats | cut -d ',' -f | read s1
     echo $s1
    

But neither scenario is working.

Best Answer

You can use something like this, for a single line of input:

IFS="," read -ra arr <<< "$foo"

Demo:

$ cat t.sh 
foo="3,aac-lc, 93.8, aaclc, 77.3, h.264, 1024.6, ..." # snipped

IFS="," read -ra arr <<< "$foo"
echo ${#arr[@]}
echo ${arr[0]}
echo ${arr[30]}
$ ./t.sh 
31
3
1280 720

Credits: Split string based on delimiter in bash? answer by Johannes Schaub. Check the other answers there too.

Related Question