9.4 Reading comma-separated CSV files using the read utility but no file descriptor

In the following example we are going to read a csv file called example.csv. The file has five columns (five fields per line). We are going to use the while loop to iterate through each line of the csv file and save the fields in variables f1, f2, f3, f4. Before starting to iterate, we have to tell bash that comma (,) will be the separator in each line: IFS=','.

$ IFS=','
$ i=1
$ while read f1 f2 f3 f4
> do
> echo "Line $((i++)):"
> echo "Field 1: $f1"
> echo "Field 2: $f2"
> echo "Field 3: $f3"
> echo "Field 4: $f4"
> done < example.csv
Line 1:
Field 1: "SUBJ1"
Field 2: "Age 22-30"
Field 3: "VISIT1"
Field 4: "DIAGN: Major Depressive Disorder, Single Episode"
Line 2:
Field 1: "SUBJ2"
Field 2: "Age 22-30"
Field 3: "VISIT1"
Field 4: "DIAGN: Bipolar, Schizophrenia"
Line 3:
Field 1: "SUBJ3"
Field 2: "Age 22-30"
Field 3: "VISIT1"
Field 4: "DIAGN: Major Depressive Disorder"
Line 4:
Field 1: "SUBJ4"
Field 2: "Age 22-30"
Field 3: "VISIT1"
Field 4: "DIAGN: Autism, Dyslexia, ADHD"