Hi skuthe,
Just at a glance I see 2 problems:
PROBLEM 1:
You commented out the delete of ARGV[j]:
# delete ARGV[j];
The delete is necessary because of the way awk handles command line arguments.
Let me explain it this way:
Awk lets you define variables on the command line that can be referenced in the program using the syntax awk myvar=value. (There is more to this syntax, including the use of the -v switch, but I won't get into that now).
One of the problems is that, at least on my version of awk, variables defined in this way are not accessible in the BEGIN{} section, they are only accessible in main.
Another thing -- and this is a personal preference -- is that I often prefer to minimize the extra stuff that has to be written on the command line, so I sometimes like to get rid of the 'myvar=' portion of the variable definition.
But if you don't use the syntax to tell awk that an argument is a variable, awk assumes it is an input file. (I don't know if you have ever tried this, but if you put 2 or more file names on your command line, awk will process them in the order supplied).
So, when we ask the user to supply the column numbers on the command line without anything to signal that it is a variable, then we can access those values in the BEGIN{} section via the ARGV[] array, but we need to remember to delete those values from the ARGV[] array, or awk will think they are filenames when the main loop starts, and it will bomb out because no files exist by those names. (Or if files do exist with the same name, things might get really hairy!)
PROBLEM 2:
You copied some of the code incorrectly. You have:
for (j=1; j<=MaxCols; j++)
{
ColVal[j]=$(ColNo[j]);
ColStr=ColVal[1];
}
for (j=2; j<=MaxCols; j++)
ColStr=ColStr SUBSEP ColVal[j];
It should be:
for (j=1; j<=MaxCols; j++)
{
ColVal[j]=$(ColNo[j]);
}
ColStr=ColVal[1];
for (j=2; j<=MaxCols; j++)
{
ColStr=ColStr SUBSEP ColVal[j];
}
This was an easy mistake to make because in the original code I did not clearly delineate the scope of the for block with the use of {}'s. Normally I do, but sometimes I can be a slacker.
Try it again with those corrections and let me know how it goes.
Grant.
Question: Has anybody ever tried using array references on the command line?
Example: my.awk col[1]=1 col[2]=3 col[3]=5 mydata.txt
A usage like this (if it works) might make for a messier command line, and increase the possibility of user error, but it might make the program code simpler and easier to understand. This would only be needed in cases where there was a need for a varying number of arguments, such as column numbers.