Reputation: 65
I have a text file with matrices
A: 1, 2, 3, 4
B: 2, 4, 6, 8; 1, 2, 5, 6
C: 8, 6, 4, 2; 1, 2, 3, 4; 1, 3, 5, 7
and I want to read this file in shell script, store these matrices in different arrays and then use these arrays for further computation (addition and subtraction only). Here is my code:
#! /bin/bash
R=`awk -F'[^0-9]+' '{$1=$1; print;}' testfile.txt`
echo $R;
this gives me an output in this form:
1 2 3 4 2 4 6 8 1 2 5 6 8 6 4 2 1 2 3 4 1 3 5 7
I tried using loops to put these in different arrays but that didn't work for some reason. Can anyone help me with this?
(i am new to shell scripting so a little explanation with your code solution would be really helpful. thanks)
Upvotes: 1
Views: 1735
Reputation: 19375
This will store the matrix values in the arrays A, B and C:
IFS+=,\;
eval `
while read name numbers
do if [ $name ]
then echo "${name%:}=($numbers)"
fi
done <testfile.txt
`
This will output the different arrays, just for checking purposes:
echo ${A[*]}
echo ${B[*]}
echo ${C[*]}
Since bash provides only one-dimensional arrays, we have to compute an index given the row size, e. g.
row=2; col=3
echo ${C[$row*4+$col]}
Upvotes: 0
Reputation: 48280
One of the Laws of Programming is that parsing input is often more difficult than the entire remainder of the exercise.
To get started, you can try using either cut
or the Internal Field Separator several times on each line.
First use :
as the delimiter to separate the array name from the values.
Then use ;
as the delimiter to separate the rows.
Finally, use ,
as the delimiter to get the individual values.
Upvotes: 1