I am learning to script in Bash.
I have a CSV file with 5 columns and 22 rows. I am interested in taking the data from the second column and put it into 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]}"
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]}"
i like to use awk
. First split based on ,
delimiter and take required column values into array.
abc=($(tail -n +1 MyAssignment.csv | awk -F ',' '{print $2;}'))
echo ${abc[1]}
Index start from 1. If the file contains headers, replace +1
with +2
to ignore headers.