how to convert from csv to array in bash

I'm new on bash and I want to convert a csv file to different arrays. My csv has 6 lines with same number of columns each and I need to take lines 3,4,5 and 6 with all columns and make and array out of every line, any idea how can I do that?

My csv looks like:

  1. A, B, C, ...
  2. 1, 1, 1,...
  3. 7, 23, 58,...
  4. 8, 24, 59,...
  5. 9, 25, 60,...
  6. 10, 26, 61,...

And I want my output to look like:

array1=(7,23,58,...)

array2=(8,24,59,...)

array3=(9,25,60,...)

array4=(10,26,61,...)

Many thanks

Upvotes: 0

Views: 1146

Answers (1)

fxdeaway
fxdeaway

Reputation: 165

Note: The script below will result in an extra empty array but it should do the job.

Parsing .csv files with Bash is probably not the most efficient but there is a way to do it. Note that arrays in Bash are separated by space, not ,.

In the example below, the input .csv file is input.csv and the output file is output.txt.

#!/bin/bash
{
    read
    read
    var=0
    while IFS=, read -a arr
    do
        var=$((var+1))
        echo "array${var}=(${arr[@]})" >> output.txt
    done 
} < input.csv

More explanation
* The two lines of read is the key here: it reads the first two lines of your .csv input and then enters the loop, when it is going to start reading the third line.
* According to the documentation here, the -a flag assigns the words read to sequential indices of the array variable ARRAY, starting at zero.
* "@" is used to access all the values in the generated array resulting from read -a

Edited my script based on @Poshi's suggestion. Script looks cleaner now.

Upvotes: 1

Related Questions