Array of arrays in bash

前端 未结 6 1137
日久生厌
日久生厌 2020-12-24 05:09

I\'m attempting to read an input file line by line which contains fields delimited by periods. I want to put them into an array of arrays so I can loop through them later on

6条回答
  •  暖寄归人
    2020-12-24 05:49

    You could make use of (de)referencing arrays like in this script:

    #!/bin/bash
    
    OFS=$IFS     # store field separator
    IFS="${2: }" # define field separator
    file=$1      # input file name
    
    unset a      # reference to line array
    unset i j    # index
    unset m n    # dimension
    
    ### input
    
    i=0
    while read line
    do
      a=A$i
      unset $a
      declare -a $a='($line)'
      i=$((i+1))
    done < $file
    # store number of lines
    m=$i
    
    ### output
    
    for ((i=0; i < $m; i++))
    do
      a=A$i
      # get line size
      # double escape '\\' for sub shell '``' and 'echo'
      n=`eval echo \\${#$a[@]}`
      for (( j = 0; j < $n; j++))
      do
        # get field value
        f=`eval echo \\${$a[$j]}`
        # do something
        echo "line $((i+1)) field $((j+1)) = '$f'"
      done
    done
    
    IFS=$OFS
    

    Credit to https://unix.stackexchange.com/questions/199348/dynamically-create-array-in-bash-with-variables-as-array-name

提交回复
热议问题