[英]How to read and split comma separated file in a bash shell script?
我想逐行读取文件,用逗号(,)分隔每一行并将结果存储在数组中。 如何在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
从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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.