How to read in csv file to array in bash script

2019-06-05 08:39发布

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

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.

Help is much appreciated!

1条回答
forever°为你锁心
2楼-- · 2019-06-05 09:16

You may consider using AWK with a regular expression in FS variable like this:

 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)

查看更多
登录 后发表回答