简体   繁体   English

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

[英]How to read in csv file to array in bash script

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. 我编写了以下代码,以将我的csv文件(具有固定的列数但没有固定的行数)作为数组读入脚本。 I need it to be a shell script. 我需要它是一个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. 对于这两者,我尝试了一些测试代码来查看数组行的大小,并且第一个似乎是10,但是数组仅输出用户名。 For the second one, I seem to be getting a size of 0 but the array outputs the whole csv. 对于第二个,我似乎得到的大小为0,但数组输出整个csv。

Help is much appreciated! 非常感谢帮助!

You may consider using AWK with a regular expression in FS variable like this: 您可以考虑将AWKFS变量中的正则表达式一起使用,如下所示:

 awk 'BEGIN { FS=",?[ \t]*"; } { print $1,"|",$2,"|",$3,"|",$4,"|",$5; }'

or this 或这个

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

( $1=$1 is required to rebuild $0 with new OFS) (需要$1=$1才能用新的OFS重建$ 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM