I am currently writing an awk script within a bash script. One of my arguments needs to be split and cycled through. Eg: for an argument of 1234 I need to cycle through each number in the order written. So, 2413 is not equivalent.
I used split to create an array and then a for-in loop to cycle through the array. I assumed it would cycle through in order, but it is not.
My code is as follows:
split(cols,toShow,"")
for (c in toShow)
printf "%s\n",c
cols is passed to the awk command using the -v option and gives the following output:
4
1
2
3
After testing this a few times, with varying lengths of arguments and using both numbers and letters, it appears that the for loop starts at element 4 of the array, cycles through to the end in order, then cycles through elements 1 to 3, instead of the expected starting at element 1 and cycling to the end.
Is there anyway to change the behaviour or am I doing something wrong?
EDIT For clarification, I am using gawk in xubuntu 11.10
arrays in awk aren’t (necessarily) stored in the order from the original source.
Also, using numbers as your input is confusing the issue
Here is a solution that will illustrate the problem
** output**
To see what I mean, edit your code to ABCD and you’ll still the your numeric output as
for c in toShowis printing the keys and not the values of the assoc array.If you edit ABCD in my sample, to 1234, you’ll get the output you’re looking for.
I hope this helps.