I want to print the second last column or field in awk. The number of fields is variable. I know that I should be able to use $NF
but not sure how it can be used.
And this does not seem to work:
awk ' { print ( $NF-- ) } '
I want to print the second last column or field in awk. The number of fields is variable. I know that I should be able to use $NF
but not sure how it can be used.
And this does not seem to work:
awk ' { print ( $NF-- ) } '
Perl solution similar to Chris Kannon's awk solution:
These command-line options are used:
n
loop around every line of the input file, do not automatically print every linel
removes newlines before processing, and adds them back in afterwardsa
autosplit mode – split input lines into the@F
array. Defaults to splitting on whitespacee
execute the perl codeThe
@F
autosplit array starts at index [0] while awk fields start with $1.$#F
is the number of elements in@F
Should work
It's simplest:
The reason the original
$NF--
didn't work is because the expression is evaluated before the decrement, whereas my prefix decrement is performed before evaluation.Did you tried to start from right to left by using the rev command ? In this case you just need to print the 2nd column:
Small addition to Chris Kannon' accepted answer: only print if there actually is a second last column.