Hello, all
For a 1-dimensional array, such as
myarr_1[AA]=1
myarr_1[BB]=2
myarr_1[CC]=3
I know I can write a loop as below to show the array member one by one:
for (i in myarr_1){print i, myarr_1}
Now, suppose I have a two dimensional array such as:
myarray_2[1,AA]=1 myarray_2[1,BB]=2
myarray_2[2,AA]=10 myarray_2[2,BB]=20
My questions are:
1.how to write code to print the array member one by one?
2.how to write code to only print "myarray_2[1,AA]", "myarray_2[1,BB]"?
awk does not actually have two-dimensional arrays; it handles two indexes by squeezing them into a single string. As such, your first loop will work but may look weird; the SUBSEP character which it puts between them defaults to a nonprinting ASCII character but can be anything you set it to.
I don't know of a way to iterate over only part of an array. The best I think you can do is iterate over the whole array, and ignore the parts you don't want.
for(X in ARR) {
split(X, Q, SUBSEP);
if(Q[1] != "5") continue;
print Q[1], Q[2], ARR[X];
}
1 Like
You can also do something like this:
awk '{A[$1,$2]=$3; I[$1]; J[$2]} END{ for(i in I)for(j in J) print i, j, A[i,j]}' file
or for example:
awk '{A[$1,$2]=$3; J[$2]} END{ for(j in J) print 5, j, A[5,j]}' file
1 Like