gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:17:32 26 4
gpt4 key购买 nike

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

最佳答案

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

来自帮助阅读:

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

关于arrays - 如何在 bash shell 脚本中读取和拆分逗号分隔的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25263521/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com