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条回答
Ridiculous、
2楼-- · 2019-01-10 05:22

Perl solution similar to Chris Kannon's awk solution:

perl -lane 'print $F[$#F-1]' file

These command-line options are used:

  • n loop around every line of the input file, do not automatically print every line

  • l removes newlines before processing, and adds them back in afterwards

  • a autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace

  • e execute the perl code

The @F autosplit array starts at index [0] while awk fields start with $1.
$#F is the number of elements in @F

查看更多
干净又极端
3楼-- · 2019-01-10 05:25
awk '{print $(NF-1)}'

Should work

查看更多
叼着烟拽天下
4楼-- · 2019-01-10 05:28

It's simplest:

 awk '{print $--NF}' 

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.

查看更多
淡お忘
5楼-- · 2019-01-10 05:28
awk ' { print ( $(NF-1) ) }' file
查看更多
在下西门庆
6楼-- · 2019-01-10 05:35

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:

seq 12 | xargs -n5 | rev | awk '{ print $2}' | rev
4
9
11
查看更多
7楼-- · 2019-01-10 05:38

Small addition to Chris Kannon' accepted answer: only print if there actually is a second last column.

(
echo       | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1     | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2   | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2 3 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
)
查看更多
登录 后发表回答