I have the following CSV File called test.csv
First Line, 100
Second Line, 200
Third Line, 300
Fourth Line, 400
I want to split each line at the comma and store the first part into an array in a bash script using awk. I have done the following:
#!/bin/bash
declare -a MY_ARRAY
MY_ARRAY=$(awk -F ',' '{print $1}' test.csv)
echo 'Start'
for ENTRY in ${MY_ARRAY}
do
echo ${ENTRY}
done
echo 'Stop'
And the output is as follows:
Start
First
Line
Second
Line
Third
Line
Fourth
Line
Stop
How can I get the array to hold the following?:
First Line
Second Line
Third Line
Fourth Line
awkto populate a bash array? In every case it would be easier to use bash directly. Because of the spaces inside the fields you need more bash code thanarray=( $(awk ...) )anyway (note the( )around $( )`; you forgot them).MY_ARRAY=( $(awk ... ) ); b) since theawkoutput lines contain white space you need to redefine the default field separator as a\nfor proper parsing into the array, eg,IFS=$'\n' MY_ARRAY=( $(awk ... ) )(all on one line so theIFSredefinition only applies to this command); c) to reference the individual elements of the array you need a wildcard match for the index (wrapped in[]'s), eg,for ENTRY in "${MY_ARRAY[@]}"