zyan94
zyan94

Reputation: 11

What method should I use to parse csv files in bash

I'm trying to parse numbers in a csv file which are all in one single line and delimited by a semicolon.

This is what I get after this command cat Input.csv

1;3;2;1;4;2;4;5;3;2;5;2;7;3;9;14;5;12;3;2;15;4;10;2;5;3;7;8;11;2;9;12;5;1;11;8;3;4;9;13;13;12;1;12;11;4;7;11;10;9

I've tried using while IFS=";" read , but since the whole input is in the same line, it's only possible if i create 50 variables which is not particularly practical.

The task i need to complete is to simulate a FIFO scheduling algorithm, hence I first need to read all values from the csv file which I'm currently stuck.
Do I use while or for or other method ?

Upvotes: 1

Views: 622

Answers (1)

glenn jackman
glenn jackman

Reputation: 247210

This is repeating a deleted but correct answer

IFS=";" read -r -a array < Input.csv
declare -p array

That reads the first line of the input file, splits on semi-colons and stores into the array variable named array.

The -r option for the read command means any backslashes in the input are handled as literal characters, not as introducing an escape sequence.
The -a option reads the words from the input into an array named by the gived variable name.

At a bash prompt, type help declare and help read.

Also find a bash tutorial that talks about the effect of IFS on the read command, for example BashGuide
The bash tag info page has tons of resources.

Upvotes: 2

Related Questions