如何在bash shell脚本中读取和拆分逗号分隔文件?

时间:2014-08-12 11:48:30

标签: arrays bash shell split

我想逐行读取文件,用逗号(,)分隔每一行并将结果存储在数组中。如何在bash shell脚本中执行此操作?

逗号分隔文件中的示例行

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

这应该是拆分后的输出:

arr[0]=123 arr[1]=2014-07-21 10:01:44 arr[2]=123|8119|769.00||456|S

1 个答案:

答案 0 :(得分:10)

使用read -a根据IFS将读取的每一行拆分为数组。

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

如果第三个字段也可以包含逗号,则可以使用有限的非数组参数来阻止它被分割:

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

来自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