How to print last two columns using awk
You can make use of variable NF
which is set to the total number of fields in the input record:
awk '{print $(NF-1),"\t",$NF}' file
this assumes that you have at least 2 fields.
@jim mcnamara: try using parentheses for around NF
, i. e. $(NF-1)
and $(NF)
instead of $NF-1
and $NF
(works on Mac OS X 10.6.8 for FreeBSD awk
and gawk
).
echo '
1 2
2 3
one
one two three
' | gawk '{if (NF >= 2) print $(NF-1), $(NF);}'
# output:
# 1 2
# 2 3
# two three
awk '{print $NF-1, $NF}' inputfile
Note: this works only if at least two columns exist. On records with one column you will get a spurious "-1 column1"