Reputation: 1875
Suppose I have a CSV input file called input.csv:
1,2,3,valueIWantToPrint
3,5,2,valueIWantToPrint
I currently need to print the last element of each row of that input with awk, which is easily accomplished with the field separator and NF variables:
awk -F"," '{print $NF}' input.csv
But now let's say that I want to make the field that I want to print a variable, because later perhaps the input format will change and it will be a different field.
Input file:
1,2,valueIWantToPrint,3
3,5,valueIWantToPrint,2
Script:
FIELD_TO_PRINT=3
awk -F"," -v fieldToPrint=FIELD_TO_PRINT '{print $fieldToPrint}' input.csv
Ok, that was easy. But now to make it as flexible as possible, I would like have the ability to set FIELD_TO_PRINT to the equivalent of NF so that I can print the last value regardless of the number of fields. What I'm after is something like this:
Input:
1,2,3,7,2,5,23,1,3,6,valueIWantToPrint
3,5,2,6,3,valueIWantToPrint
This script doesn't work, but illustrates what I am trying to accomplish:
FIELD_TO_PRINT=NF
awk -F"," -v fieldToPrint=FIELD_TO_PRINT '{print $fieldToPrint}' input.csv
Is there a convenient way to set a variable to mean "the last field in record?" This example is pretty trivial, but ultimately the FIELD_TO_PRINT variable will be put in a separate configuration file, and the awk script will be much larger and more complex. So having a good way to accomplish this will be very useful.
Upvotes: 3
Views: 171
Reputation: 67507
you can use this trick
$ awk -F, -v n=-1 '{print (n<0)?$(NF+n+1):$n}' file
valueIWantToPrint
valueIWantToPrint
assume negative indices start counting from NF backwards, so -2 will mean the penultimate field etc.
Upvotes: 3
Reputation: 785156
You can use this round-about way:
Negative n
means NF
:
n=-1
awk -F, -v n="$n" '{print (n<0 ? $NF : $n)}' f.csv
valueIWantToPrint
valueIWantToPrint
and when n > 0
print numbered field:
n=3
awk -F, -v n="$n" '{print (n<0 ? $NF : $n)}' f.csv
3
2
Upvotes: 3