【问题标题】:How to read and split comma separated file in a bash shell script?如何在 bash shell 脚本中读取和拆分逗号分隔的文件?
【发布时间】:2014-10-05 11:26:05
【问题描述】:

我想逐行读取文件,用逗号 (,) 分割每一行并将结果存储在一个数组中。如何在 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

【问题讨论】:

  • 你想如何处理多行?第二行的第一个字段会放在arr[3] 中吗?还是数组一次只需要保存一行,在每次迭代时重置?
  • 你可能想看看下面的answer

标签: arrays bash shell split


【解决方案1】:

使用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

【讨论】:

    猜你喜欢
    • 2020-04-04
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    相关资源
    最近更新 更多