0

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

5
  • Please add sample input (no descriptions, no images, no links) and your desired output for that sample input to your question (no comment). Commented Apr 10, 2020 at 19:27
  • What is your field separator? , or , followed by a space? Is first column with 1,2,3,4,5,6 part of your file? Commented Apr 10, 2020 at 20:17
  • the field separator is just "," , and the first column it's not part of the file Commented Apr 10, 2020 at 20:29
  • 1
    It looks like you're on the way to do something inefficient or "dangerous". Can you explain what is your goal? Have you ever heard of awk? It may be just what you want. Commented Apr 10, 2020 at 21:03
  • Does this answer your question? How to read in csv file to array in bash script Commented Apr 10, 2020 at 23:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Take a look at -e parameter of echo. Also, echo "array${var}=(${arr[*]})" >> output.txt could simplify things quite a lot. This is assuming there are no spaces in the fields.
Excellent suggestion. I will test that and update my script above once I am sure it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.