Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read columns from csv file into array in bash

Tags:

bash

csv

I have one csv file that is looking like this

NameColumn1;NameColumn2;NameColumn3;NameColumn4
Row1;Row1;Row1;Row1;
Row2;Row2;Row2;Row2;
Row3;Row3;Row3;Row3;

I want to take the values in Row1, Row2 and Row3 from NameColumn1 and put them into array,the same for NameColumn2,NameColumn3 and NameColumn4.

I don't know how much rows I will have but I know the number of columns. Any help?

Thank you.

like image 259
Golden Avatar asked Jul 15 '26 08:07

Golden


1 Answers

With the -a option/flag from the builtin read.

#!/usr/bin/env bash

while IFS=';' read -ra array; do
  ar1+=("${array[0]}")
  ar2+=("${array[1]}")
  ar3+=("${array[2]}")
  ar4+=("${array[3]}")
done < file.csv                                                       

printf '%s\n' "${ar1[@]}" "${ar2[@]}" "${ar3[@]}" "${ar4[@]}"
  • Just need to remember that index of an array starts counting at zero.
  • The only advantage of this solution is that you don't need a variable to assign each field.
like image 68
Jetchisel Avatar answered Jul 18 '26 05:07

Jetchisel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!