Print second last column/field in awk

2019-01-10 05:04发布

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-- )  } '

标签: awk gawk
9条回答
倾城 Initia
2楼-- · 2019-01-10 05:39

If you have many columns and want to print all but not the three cloumns in the last, then this might help

awk '{ $NF="";$(NF-1)="";$(NF-2)="" ; print $0 }'

查看更多
乱世女痞
3楼-- · 2019-01-10 05:39

First decrements the value and then print it -

awk ' { print $(--NF)}' file

OR

rev file|cut -d ' ' -f2|rev
查看更多
仙女界的扛把子
4楼-- · 2019-01-10 05:46

You weren't far from the result! This does it:

awk '{NF--; print $NF}' file

This decrements the number of fields in one, so that $NF contains the former penultimate.

Test

Let's generate some numbers and print them on groups of 5:

$ seq 12 | xargs -n5
1 2 3 4 5
6 7 8 9 10
11 12

Let's print the penultimate on each line:

$ seq 12 | xargs -n5 | awk '{NF--; print $NF}'
4
9
11
查看更多
登录 后发表回答