简体   繁体   中英

How to extract values from a csv file to Unix Shell Script

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.

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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