BASH - How to extract data from a column in CSV file and put it in an array?
Remove the IFS=","
assignment thereby letting the default IFS value of space, tab, newline apply
#!/bin/bash
eCollection=( $(cut -d ',' -f2 MyAssignment.csv ) )
printf "%s\n" "${eCollection[0]}"
Explained: The eCollection
variable is an array due to the outer parenthesis. It is initialized with each element from the IFS-separated (think function or command line arguments) words which come from the $(cut -d ',' -f2 MyAssignment.csv)
subshell, which is the cut
command used with the ','
delimiter and printing the second field -f2
from the MyAssignment.csv
file.
The printf
statement just shows how to print any item by index, you could also try echo "${eCollection[@}]}"
to see all of the elements.
Two pure 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]}"
Better is to use readarray
. No need to mind about IFS which could have any value, and is safe from pathname expansion.
readarray -t eCollection < <(cut -d, -f2 MyAssignment.csv)
printf '%s\n' "${eCollection[0]}"