Bash - populate 2D array from file

喜你入骨 提交于 2019-12-02 04:01:49

There's an easy way to encode a 2-dimensional array of size M×N into a 1-dimensional array of size M*N, for example:

A[p,q] ↔ B[p+q*M]

For our task: we'll fix M and N from the beginning, set all the array terms to . and then read the file to set the corresponding fields to X:

#!/bin/bash

M=10
N=10

[[ $1 && -f $1 && -r $1 ]] || { printf >&2 'arg must be readable file.\n'; exit; }
geneFile=$1

array=()
for ((i=0; i<M*N; ++i)); do
    array+=( '.' )
done

while read -r x y; do
    [[ $x && $y ]] || continue
    [[ $x = +([[:digit:]]) && $y = +([[:digit:]]) ]] || continue
    ((x=10#$x,y=10#$y))
    (( x<M && y<N )) || continue
    array[x+y*M]=X
done < "$geneFile"

# print to stdout
for((i=0;i<N;++i)); do
    printf '%s' "${array[@]:i*M:M}" $'\n'
done

With your data, output is:

..........
..........
.X........
..........
..........
..........
..........
...X......
..........
..........

In this case, another possibility is to use a string instead of an array (details left to the reader or to another answerer).

Note: the loop that reads the file silently discards malformed lines.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!