Bash - populate 2D array from file

前端 未结 1 1569
半阙折子戏
半阙折子戏 2021-01-24 02:22

I know it\'s probably something easy but i\'m struggling really hard with this.

Problem description: I have a text file with coordinates in format:
1 2
3 7 ... <

相关标签:
1条回答
  • 2021-01-24 02:59

    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.

    0 讨论(0)
提交回复
热议问题