how can i read text file and assign its values to variables using shell

Hello,

I have a cat.dat file, i would like shell to read each 3 lines and set this 3 lines to 3 different variables.

my cat.dat is:
11
12
+380486461001
12
13
+380486461002
13
14
+380486461003

i want shell to make a loop and assign 1st line to student_id, 2nd line to studentaccount and 3th line to studentinfo, and continuining on this way for each 3 lines respectively.

I wrote this code, but i am not able to assign this 3 variables :confused:
#!/bin/bash
a=0
while read line
do a=$(($a+1));

echo q=$line;
done < "cad.dat"
echo "Final line count is: $a";

I really appreciate any help, thank you in advance :).

You can do something like that :

while read student_id && read student_account && read student_info
do
   (( student_count++ ))
   echo "student #$student_count id=$student_id account=$student_account info=$student_info"
done < cat.txt
echo "Final student count: $student_count"

Input file:

11
12
+380486461001
12
13
+380486461002
13
14
+380486461003

Output:

student #1 id=11 account=12 info=+380486461001
student #2 id=12 account=13 info=+380486461002
student #3 id=13 account=14 info=+380486461003
Final student count: 3

Jean-Pierre.

cat filename | paste - - - | awk '{student [NR]=$1;account[NR]=$2;info[NR]=$3} END { for (i=1;i<=NR;i++) print student [i], account[i], info [i]}'

Thanks a lot, it works very fine. I appreciate it :b::slight_smile:

cat filename | paste -d"," - - - | awk 'BEGIN{FS=","}{print "ID="$1" A/C="$2" INFO="$3}'