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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25263521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:06:09  来源:igfitidea点击:

How to read and split comma separated file in a bash shell script?

arraysbashshellsplit

提问by user3492304

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?

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

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

回答by konsolebox

Use read -ato split each line read into array based from IFS.

用于read -a将读取的每一行拆分为基于 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:

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