如何在 BASH 中将 csv 文件读入二维数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3017128/
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-17 22:11:49  来源:igfitidea点击:

How do you read a csv file into a two dimensional array in BASH?

arraysbashcsvshell

提问by Matt Pascoe

How do you read a csv file into a two dimensional array in BASH? The script needs to be dynamic enough where it can take csv files with variable number of rows and columns.

如何在 BASH 中将 csv 文件读入二维数组?该脚本需要足够动态,以便它可以使用具有可变行数和列数的 csv 文件。

For example, if I have a csv file that looks like

例如,如果我有一个看起来像的 csv 文件

AVERAGE     STDEV     MAX
17          18        19

or

或者

AVERAGE     STDEV     MAX     MIN
17          18        19      1

回答by Paused until further notice.

One way to simulate a two-dimensional array is to keep the rows as strings in a one-dimensional array and unpack them at each iteration. You will have to choose a suitable delimiter that doesn't appear in the data. Since you mention CSV, I'll use a comma, but this won't be smart enough to handle data like this with embedded commas:

模拟二维​​数组的一种方法是将行作为一维数组中的字符串保留,并在每次迭代时将它们解包。您必须选择一个没有出现在数据中的合适的分隔符。既然您提到了 CSV,我将使用逗号,但这不够聪明,无法使用嵌入的逗号处理这样的数据:

name, start date, visits, games, balance
"Williamson, Dennis", "January 11, 2007", 12, 42, 17000

Here's a simple example of iterating over the values in a simulated two-dimensional array:

这是迭代模拟二维数组中的值的简单示例:

# avg, stddev, max, min
data_array=(
            "17,18,19,1"
            "12,14,16,2"
            "6,8,10,3"
            )

saveIFS=$IFS

for row in ${data_array[@]}
do
    IFS=","
    cols=($row)
    IFS=$saveIFS
    for col in ${cols[@]}
    do
        newval=$(do_something $col)
    done
done

Making changes to the contents of the array is possible:

可以对数组的内容进行更改:

rowidx=2
colidx=2
IFS=","
cols=(${data_array[rowidx]})
cols[colidx]=$some_value
data_array[rowidx]="${cols[*]}"
IFS=$saveIFS

As you can see, it gets complicated fast and there are lots of gotchas which I haven't mentioned. Use Python.

正如您所看到的,它很快变得复杂,并且有很多我没有提到的问题。使用 Python。

回答by jim mcnamara

bash supports only one-dimensional arrays. To see an emulation of 2 dimensions check out twodim.sh in the advanced bash scripting guide:

bash 仅支持一维数组。要查看二维仿真,请查看高级 bash 脚本指南中的 twodim.sh:

example 27.17 in

示例 27.17 中

http://tldp.org/LDP/abs/html/arrays.html

http://tldp.org/LDP/abs/html/arrays.html

And I agree this does sound like homework.

我同意这听起来像家庭作业。