BASH - How to extract data from a column in a CSV file and put it in an array?

I am participating in a script in Bash.

I have a CSV file with 5 columns and 22 lines. I am interested in taking data from the second column and putting it in an array.

I want the first name to be in array[0] , the second to array[1] , etc.

Bash script:

 #!/bin/sh IFS="," eCollection=( $(cut -d ',' -f2 MyAssignment.csv ) ) printf "%s\n" "${eCollection[0]}" 

CSV is as follows. No title bar.

The column with Vl18xx numbers is what I want to split into an array.

 John,Vl1805,VRFname,10.9.48.64/28,10.9.48.78 John,Vl1806,VRFname,10.9.48.80/28,10.9.48.94 John,Vl1807,VRFname,10.9.48.96/28,10.9.48.110 John,Vl1808,VRFname,10.9.48.112/28,10.9.48.126 John,Vl1809,VRFname,167.107.152.32/28,167.107.152.46 

bash script doesn't put 2nd column in array, what am I doing wrong?

+4
source share
3 answers

Remove IFS="," , thereby allowing you to use the default IFS value, tab, new line

 #!/bin/bash eCollection=( $(cut -d ',' -f2 MyAssignment.csv ) ) printf "%s\n" "${eCollection[0]}" 
+10
source

Two clean bash solutions:

 eCollection=() while IFS=',' read -r _ second _; do eCollection+=("$second") done < file.txt printf '%s\n' "${eCollection[0]}" 


 readarray -t eCollection < file.txt eCollection=("${eCollection[@]#*,}") eCollection=("${eCollection[@]%%,*}") printf '%s\n' "${eCollection[0]}" 
+8
source

Better to use readarray . No need to worry about IFS, which can be of any value and safe from extending the path.

 readarray -t eCollection < <(cut -d, -f2 MyAssignment.csv) printf '%s\n' "${eCollection[0]}" 
+5
source

Source: https://habr.com/ru/post/1501038/


All Articles