1

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!

2
  • read two times. with , and white space. Commented Mar 10, 2014 at 2:05
  • Note that there must not be any whitespace in variable assignments, so set oldIFS = $IFS should be set oldIFS=$IFS. Also, your sample data is a mixture of comma- and whitespace-separated fields. Is that how your input data is actually looking? If not, please provide an accurate example. Commented Mar 10, 2014 at 9:31

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.