0

From a unix shell scripting file, I want to extract the values in a csv file. Suppose, I have a csv file values.csv with headers V1, V2 and N like below:

"V1","V2","N"
"0","0",216856
"1","0",16015
"0","1",25527
"1","1",10967

I want to extract the column N values and assign it to a variable in a unix script file. For example,

a = 216856
b = 16015
c = 25527
d = 10967

How will you pull the values of N and assign to the variables a,b,c,d in a shell script file? Please help. Thanks in advance.

2 Answers 2

1

Don't use individual variable names, use an array. Install csvkit, then

mapfile -t n < <(csvcut -c "N" file.csv)

echo "a = ${n[1]}"
echo "b = ${n[2]}"
echo "c = ${n[3]}"
echo "d = ${n[4]}"

Note that CSV can be surprisingly tricky to parse, so use a proper CSV parser.

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

Comments

0

This will work in Bash, assuming you would want to use arrays, which is the right way to do this :

 array=( $( tail -n +2 values.csv | awk -F',' '{print $3}'  | tr '\n' ' ' ) )
 echo "${array[0]}"

Regards!

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.