如何在 bash 脚本中读取 csv 文件到数组

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

How to read in csv file to array in bash script

arrayslinuxbashshellcsv

提问by user3399613

I have written the following code to read in my csv file (which has a fixed number of columns but not a fixed number of rows) into my script as an array. I need it to be a shell script.

我编写了以下代码以将我的 csv 文件(具有固定数量的列但不固定数量的行)作为数组读取到我的脚本中。我需要它是一个shell脚本。

usernames   x1    x2   x3  x4
username1,  5     5    4   2
username2,  6     3    2   0
username3,  8     4    9   3

My code

我的代码

#!/bin/bash
set oldIFS = $IFS
set IFS=,
read -a line < something.csv

another option I have used is

我使用的另一个选项是

#!/bin/bash
while IFS=$'\t' reaad -r -a line
do 
echo $line
done < something.csv

for both I tried some test code to see what the size of the array line would be and I seem to be getting a size of 10 with the first one but the array only outputs username. For the second one, I seem to be getting a size of 0 but the array outputs the whole csv.

对于两者,我都尝试了一些测试代码来查看数组行的大小,我似乎第一个的大小为 10,但数组只输出用户名。对于第二个,我似乎得到了 0 的大小,但数组输出了整个 csv。

Help is much appreciated!

非常感谢帮助!

回答by user3159253

You may consider using AWKwith a regular expression in FSvariable like this:

您可以考虑AWKFS变量中使用正则表达式,如下所示:

 awk 'BEGIN { FS=",?[ \t]*"; } { print ,"|",,"|",,"|",,"|",; }'

or this

或这个

 awk 'BEGIN { FS=",?[ \t]*"; OFS="|"; } { =; print ##代码##; }'

($1=$1is required to rebuild $0 with new OFS)

$1=$1需要用新的 OFS 重建 $0)