views:

100

answers:

2

Given the following function:

function process_pipes(text)
{
    split(text,recs,"|");
    for (field in recs){
        printf ("|%s|\n", field)
    }
}

If the input is: 0987654321|57300|ERROR account number not found|GDUMARESQ|0199|9|N|0||

Why do I get the numbers below instead of the text?

|4|
|5|
|6|
|7|
|8|
|9|
|10|
|1|
|2|
|3|
+2  A: 

Because

for ... in

gives you the keys. Use

printf("|%s|\n",recs[field]);

to get the values.

dmckee
+2  A: 

split creates an array recs in your code, and recs[1] == 0987654321, etc.

The for (field in recs) loop generates the list of indexes, not the array elements.

Hence, you need:

function process_pipes(text)
{
    split(text,recs,"|");
    for (field in recs){
        printf ("|%s|\n", recs[field])
    }
}
Jonathan Leffler
Ok, that makes sense. The example in the gawk manual isn't clear on that. That leads me to ask why it doesn't process the array in order.
jgreep
Because all arrays are treated as associative arrays, and the order seen is related to the order in which the keys present in the array are hashed. There are sort functions in gawk (asrot, asorti) that can be used to get the data in sorted order - see: http://www.gnu.org/software/gawk/manual/gawk.html#Built_002din
Jonathan Leffler