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

有些话、适合烂在心里 提交于 2020-08-04 18:37:06

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/25263521/how-to-read-and-split-comma-separated-file-in-a-bash-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!