Reputation: 85
I am new in linux and I try reading a text file line by line. The lines are numbers. I want to add each line in an array and consider each number as a variable. My trial is as below:
Example of txt file:
1976 1 0 0.00 0. 68. 37. 0. 105. 0.14 0.02 4.3 1.1 2.2
What I need:
Putting each number in a variable. for example a = 1976
and b = 1
etc...
My code:
IFS=$'\n'
for next in `cat $filename`
do
line=$next
echo ${line[0]}
done
Result:
1976 1 0 0.00 0. 68. 37. 0. 105. 0.14 0.02 4.3 1.1 2.2
Upvotes: 0
Views: 654
Reputation: 21
# Add each line to Array
readarray -t aa < $filename
# Put each line into variables using Here String
for l in "${aa[@]}"; do
read a b c <<< $l; # Example using 3 variables, could be as many as on line
# Do whatever has to be done with a, b, c, etc
done
Upvotes: 0
Reputation: 1172
It's quite easy to store each value in an array. Here is an example:
while read -r -a line
do
echo "${line[0]}"
echo "${line[1]}"
echo "${line[2]}"
done < $filename
-a line splits the input-line into words (white space seperated by default) and store the results in line
array.
A snippet from read man:
-a Each name is an indexed array variable (see Arrays above).
You man not need the '-r' option. It basically make read to treat \ as nothing special in the input.
Upvotes: 1