如何在CSV文件读取到bash脚本阵列 [英] How to read in csv file to array in bash script
问题描述
我写了下面的code在我的csv文件读取(它有一个固定的列数,但不是一个固定的行数)为我的脚本作为数组。我需要它是一个shell脚本。
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.
usernames x1 x2 x3 x4
username1, 5 5 4 2
username2, 6 3 2 0
username3, 8 4 9 3
我的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
为我尝试了一些测试code看到阵列行的大小将是什么,我似乎得到一个大小为10与第一个,但阵列只输出用户名。对于第二个,我似乎得到一个大小为0,但阵列输出整个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.
帮助是非常AP preciated!
Help is much appreciated!
推荐答案
您可以考虑使用 AWK
与常规EX pression像这样的FS
变量:
You may consider using AWK
with a regular expression in FS
variable like this:
awk 'BEGIN { FS=",?[ \t]*"; } { print $1,"|",$2,"|",$3,"|",$4,"|",$5; }'
或本
awk 'BEGIN { FS=",?[ \t]*"; OFS="|"; } { $1=$1; print $0; }'
( $ 1 = $ 1
需要重建$ 0附有新OFS)
($1=$1
is required to rebuild $0 with new OFS)
这篇关于如何在CSV文件读取到bash脚本阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!