如何阅读和拆分逗号在bash shell脚本分隔的文件? [英] How to read and split comma separated file in a bash shell script?

查看:1113
本文介绍了如何阅读和拆分逗号在bash shell脚本分隔的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要逐行读取一个文件行,用逗号(,)分割每行并将结果存储在数组中。如何做到这一点在bash shell脚本?

在我的逗号分隔的文件示例行

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

这应该是分裂后的输出:

 改编[0] = 123 ARR [1] = 2014年7月21日10时01分44秒ARR [2] = 123 | 8119 | 769.00 || 456 | S


解决方案

使用读-a 分裂读入来自IFS基于阵列的每一行。

 而IFS =读-ra ARR;做
    ##做点什么$ {arr0]} $ {ARR [1]}和$ {ARR [2]}
    ...
完成<文件

如果第三个字段也可以包含逗号,你可以prevent它采用有限非数组参数被拆:

 而IFS =读-r A B C;做
    ##做点什么$ A,$ b和$ C
    ...
完成<文件

帮助读


 读取从标准输入单行线,或者从文件描述符FD
如果-u选项提供。该线被分成领域与字
分裂,和第一个字被分配给第一个名称,所述第二
字第二个名称,依此类推,分配给任何剩余的字
姓氏。只有在$ IFS中发现的字符将被视作字
分隔符。  -a阵列分配读取到所述阵列的顺序的索引词
            变量数组,从零开始


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

解决方案

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

这篇关于如何阅读和拆分逗号在bash shell脚本分隔的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆