How to load different type of data in a file to two arrays

Hi,

I have tried to find some sort of previous similar thread on this but not quite close to what I want to achieve.

Basically I have two class of data in my file..e.g
1,1,1,1,1,2,yes
1,2,3,4,5,5,yes
2,3,4,5,5,5,no
1,2,3,4,4,2,no
1,1,3,4,5,2,no

I wanted to read the "yes" entry to an array and "no" entry into another array.

From there, I wanted to do a random selection of yes[1] or yes[2] to duplicate the existing records.The same goes for no[1],no[2] and no[3].

Could anyone shed some light on this?

I tried some partial solution below but it doesnt work:-

#!/bin/bash

awk -F, ' {


if($NF=="yes"){
  i++;
  yes=$1;
}

else if($NF=="no"){
       j++;
          no[j]=$1;
}


}' myfile

I tried to do echo ${yes[@]} and echo ${no[@]} but it doesnt print anything.

Please advise. Thanks.

An awk array is not a shell array, and if it were, it is created in a child process (awk) which cannot set a variable in the calling shell.

Try this:

yes=( grep yes$ myfile )
no=( grep no$ myfile )

Hi,

I have tried your suggestion by having that two arrays created. But when i did try echo ${yes[@]}, it print out the the command "grep yes$ myfile".

Is there any thing I missed out?

Thanks.

I'm guessing cfajohnson meant

yes=( $(grep yes$ myfile) )
no=( $(grep no$ myfile) )

Your awk script only picked out the first field, whereas this will pick out the whole lines. Which do you want? If you only want the first field, you can add a cut

yes=( $(grep yes$ myfile | cut -d, -f1) )
no=( $(grep no$ myfile | cut -d, -f1) )

Thanks Era and cfajohnson,

Appreciate alot.

But I have a question on the array..after I get that array, how could I know number of entries that the array hold?

I tried

for i in ${yes[@]}
do
total+=1;
done

echo $total

But it gives me weird total number of 11 instead.

E.g I have

1,1,1,1,1,2,yes
1,2,3,4,5,5,yes
2,3,4,5,5,5,no
1,2,3,4,4,2,no
1,1,3,4,5,2,no

The Yes total variable should give me 2 instead.

Any mistakes I did?

Please advise. Thanks.

To get the number of elements in an array:

echo ${#yes[@]}

To loop through an array (note the quotes):

for e in "${yes[@]}"; do ...