Search code examples
bashshellsolaris

Converting file to 2d array in bash


I am working on a project where I saved some data to a file (data.txt).

10010101010;99;18767654536;252525
89878337326;44;18764329087;242424

The next step now is to read that data in to a 2D array where row[0] is the first row and row[1] is the second row. I am trying to achieve that goal. Additionally I would love to be able to access the individual elements for each row also

I currently have this code but it only prints the first row and i cant access the elements

read -a rows < data.txt                                          
for row in "${rows[@]}";do                                                      
  row_array=(${row})                                                            
  first=${row_array[0]} 
  sec=${row_array[1]}                                                        
  echo ${first}
  echo ${sec}                                                                 
done

Solution

  • Following your comment, it looks like a simple while read loop is what you need :

    while IFS=';' read -r id rest; do
        if [[ "$id" == "10010101010" ]]; then
            echo "Matching line : $id $rest"
        fi
    done < data.txt
    

    In this code IFS=';' specifies to use the ; character as the internal field separator for the command read, which will make it parse each one of your lines as four distinct words.

    The names following read -r correspond to variables to use to store each of these words, the last of them containing the rest of the line if there are more words than variables.
    read -r id rest will store the first column in the $id variable and the remaining words into $rest, while read -r first second third fourth would store each word in its own variable.

    The input of the read command is specified at the end of the while loop appending < data.txt after the done closing the loop.