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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With