5

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.

Mofi
  • 46,139
  • 17
  • 80
  • 143
Golden
  • 67
  • 1
  • 1
  • 7

3 Answers3

7

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.
Jetchisel
  • 7,493
  • 2
  • 19
  • 18
5

Assuming you have four columns

 while read a b c d; do 
   ar1+=($a)
   ar2+=($b)
   ar3+=($c)
   ar4+=($d)
done < <(sed 's/;/\t/g' somefile.txt)

You then have 4x arrays called ar1 through ar4 with the column values in them.

SaintHax
  • 1,875
  • 11
  • 16
  • @DavidC.Rankin I don't think this works, `-d` makes `read` stop when encountering the delimiter. I'd say it would have to be `IFS=';'`. – Benjamin W. May 11 '16 at 23:33
  • @BenjaminW. there's no -d, it's 4 variables named a b c and d. It works, I ran it on a file I had sitting around before I posted it. – SaintHax May 12 '16 at 03:18
  • @SaintHax Absolutely - I commented on David's comment, which, by now, is gone - it contained an alternative to using sed with `read -d`, but it wouldn't have worked, which I pointed out. – Benjamin W. May 12 '16 at 03:31
  • @DavidC.Rankin But 100% support from me for a pure Bash solution ;) – Benjamin W. May 12 '16 at 03:31
1

Using @SaintHax answer and a tweak; this worked for my application and similarly formatted data. Note the addition of quotes on stored vars, and the removal of the sed command on the redirected file. Removed IFS settings, thanks to @Jetchisel 's comment.

while read -r a b c d; do 
    ar1+=("$a")
    ar2+=("$b") 
    ar3+=("$c") 
    ar4+=("$d") 
done < somefile.csv 
masher
  • 53
  • 9
  • 4
    `while IFS=';' read ....` the `OLDIFS` trick is not needed since the `IFS=';'` dies/discarded after the loop is done. – Jetchisel Jul 07 '20 at 23:08