Bash - populate 2D array from file

前端 未结 1 1590
半阙折子戏
半阙折子戏 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

    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)
提交回复
热议问题