0

I am currently working with a bash script. I have a csv file where every line looks like the following:

1,ABC DEF
2,GHI JKL

I want to create an array with only values in the second field, and then print them.

My current solution is the following:

myarr=($(awk -F, '{print $2}' filename.csv))
for i in "${myarr[@]}" 
do
    echo $i
done

My output looks like this:

ABC
DEF
GHI
JKL

When I need it to look like this:

ABC DEF
GHI JKL

I need the result to be in a variable for future operations!

How do I solve this problem?

Emma
  • 27,428
  • 11
  • 44
  • 69
niccals
  • 51
  • 2
  • 6

3 Answers3

3
mapfile -t myarr < <(awk -F, '{print $2}' filename.csv)
declare -p myarr

Output:

declare -a array='([0]="ABC DEF" [1]="GHI JKL")'

See: help mapfile, help declare

Cyrus
  • 84,225
  • 14
  • 89
  • 153
3

If you want values in shell array then don't use awk. Just use a loop like this:

arr=()
while IFS=, read _ val; do
   arr+=("$val")
done < file

# check array content
declare -p arr
declare -a arr='([0]="ABC DEF" [1]="GHI JKL")'

# loop through array
for i in "${arr[@]}"; do
   echo "$i"
   # or do whatever with individual element of the array
done
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Hi, thanks for this answer. when using `declare` i can see the array looking the way I want it to. But when I iterate over it, using the same for loop I used before, I still get the wrong output ("ABC DEF" is printed in two separate lines). – niccals Apr 27 '19 at 10:46
  • See this answer on how to iterate an array: https://stackoverflow.com/a/8880633/548225 Make sure you quote it properly as shown in answer. – anubhava Apr 27 '19 at 10:53
  • I have added sample code for looping though array. Let me know if there is any problem. – anubhava Apr 27 '19 at 18:01
2

You can also simply read the entire line into the array, then strip the first field.

mapfile -t myarr < filename.csv
myarr=("${myarr[@]#*,}")
chepner
  • 497,756
  • 71
  • 530
  • 681