RudiC and I were working on similar solutions, but he posted first... The following code performs some range checking that RudiC's code does not attempt, and includes a little bit of discussion on why you can't reference the awk NF variable in another awk variable.
Variables contain strings or numbers; not indirect references to other variables. But, if you just use positive values to reference fields 1 up to NF inclusive and numbers less than 1 to represent fields NF down to 1 ( 0 representing NF ; -1 representing NF - 1 ; -2 representing NF - 2 ; etc.), you can use something like:
#!/bin/ksh
printf '%s\n' "12 44 45 252 24" "1 2 3 4 5 6 7 8 9 10" "A B C D E F G H I J" |
awk -v COLS="${1:-"-1,4,3"}" '
BEGIN { npf = split(COLS, pf, ",")
}
{ for(i = 1; i <= npf; i++)
printf("%s%s", (pf > NF || pf < 1 - NF) ? "OutOfRange" : \
(pf < 1) ? $(NF + pf) : $pf,
(i == npf) ? ORS : OFS)
}'
which, if invoked with no arguments prints the next to the last, the 4th, and the 3rd fields by default for each line read from the three lines printed by the printf command:
252 252 45
9 4 3
I D C
And, if invoked with the operand:
./tester -5,6,0,1
which prints the 5th from the last, the 6th, the last, and the 1st fields:
OutOfRange OutOfRange 24 12
5 6 10 1
E F J A
This was written and tested with a Korn shell, but will work with any shell that performs the standard variable expansions required by the POSIX standard shell.
If you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk or nawk .