Split in awk not not printing array values

arrayawk

I have a string tstArr2 which has the following content

'3 5 8'

Now in awk I want to parse a flat file

test my array which array is better array

INDIA USA SA NZ AUS ARG GER BRA
US AUS INDIA ENG NZ SRI PAK WI BAN NED IRE

at these numbered columns only.
I tried the following

awk -vA="$tstArr2" 'BEGIN{split(A,B," ");} {if(NR>1){for(i=1; i<= length(B); i++){printf "%s ",B[i]}}print " "}' testUnix3.txt

But it says

awk: Cannot read the value of  B. It is an array name.

The input line number is 2. The file is testUnix3.txt.
The source line number is 1.

What am I missing ?
If I try the following

awk -vA="$tstArr2" 'BEGIN{split(A,B," ");} {if(NR>1){for(i in B){printf "%s ",$B[i]}}print " "}' testUnix3.txt

it prints the outputs but they are not in order. I want them to be in order.
Please explain.
Desired output :

 SA AUS BRA

 INDIA NZ WI

Best Answer

POSIX defined length in awk is a string function, argument taken as a string. Using length with an array as argument is unspecified behavior.

In some implementations of awk like gawk (version >= 3.1.6), OS X version of AWK, you can use length with an array as argument, it will return number of elements in array.

Array in awk is associative array, looping through associative array does not guarantee anything about the order. In this case, you can take advantage of split function, which return number of fields to get the number elements of array.

POSIXly, you can try:

$ awk -vA="$tstArr2" '
  BEGIN{n = split(A,B," ");}
  {
    if(NR > 1) {
      for(i = 1;i <= n;i++) {
        printf "%s ",$B[i];
      }
    }
    print " ";
  }
' file

SA AUS BRA  
INDIA NZ WI
Related Question