Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read and split comma separated file in a bash shell script?

I want to read a file line by line, split each line by comma (,) and store the result in an array. How to do this in a bash shell script?

Sample line in my comma separated file

123,2014-07-21 10:01:44,123|8119|769.00||456|S

This should be the output after splitting:

arr[0]=123 arr[1]=2014-07-21 10:01:44 arr[2]=123|8119|769.00||456|S
like image 673
user3492304 Avatar asked Aug 12 '14 11:08

user3492304


People also ask

How do I read a file in bash?

Syntax: Read file line by line on a Bash Unix & Linux shell The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line: while read -r line; do COMMAND; done < input. file. The -r option passed to read command prevents backslash escapes from being interpreted.


1 Answers

Use read -a to split each line read into array based from IFS.

while IFS=, read -ra arr; do
    ## Do something with ${arr0]}, ${arr[1]} and ${arr[2]}
    ...
done < file

If the third field can also contain commas, you can prevent it from being split by using finite non-array parameters:

while IFS=, read -r a b c; do
    ## Do something with $a, $b and $c
    ...
done < file

From help read:

Reads a single line from the standard input, or from file descriptor FD
if the -u option is supplied.  The line is split into fields as with word
splitting, and the first word is assigned to the first NAME, the second
word to the second NAME, and so on, with any leftover words assigned to
the last NAME.  Only the characters found in $IFS are recognized as word
delimiters.

  -a array  assign the words read to sequential indices of the array
            variable ARRAY, starting at zero
like image 81
konsolebox Avatar answered Sep 28 '22 04:09

konsolebox