如何使用awk打印最后两列?

时间:2022-06-01 21:59:36

All I want is the last two columns printed.

我想要的是最后两列打印出来的。

4 个解决方案

#1


162  

You can make use of variable NF which is set to the total number of fields in the input record:

您可以使用变量NF,它设置为输入记录中的字段总数:

awk '{print $(NF-1),"\t",$NF}' file

this assumes that you have at least 2 fields.

这假设您至少有两个字段。

#2


10  

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"

注意:只有在至少有两列存在时才会起作用。在有一列的记录中,你会得到一个伪的“-1列”

#3


7  

@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 awkand gawk).

@jim mcnamara:试着用圆括号来表示NF,即$(NF-1)和$(NF),而不是$NF-1和$NF(在Mac OS X 10.6.8中用于FreeBSD尴尬和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

#4


1  

using gawk exhibits the problem:

使用gawk显示问题:

 gawk '{ print $NF-1, $NF}' filename
1 2
2 3
-1 one
-1 three
# cat filename
1 2
2 3
one
one two three

I just put gawk on Solaris 10 M4000: So, gawk is the cuplrit on the $NF-1 vs. $(NF-1) issue. Next question what does POSIX say? per:

我只是把gawk放在了Solaris 10 M4000上:所以,gawk是$NF-1和$(NF-1)问题的cuplrit。下一个问题,POSIX说什么?/:

http://www.opengroup.org/onlinepubs/009695399/utilities/awk.html

There is no direction one way or the other. Not good. gawk implies subtraction, other awks imply field number or subtraction. hmm.

没有方向,也没有方向。不好的。gawk表示减法,其他的awks表示字段数或减法。嗯。

#1


162  

You can make use of variable NF which is set to the total number of fields in the input record:

您可以使用变量NF,它设置为输入记录中的字段总数:

awk '{print $(NF-1),"\t",$NF}' file

this assumes that you have at least 2 fields.

这假设您至少有两个字段。

#2


10  

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"

注意:只有在至少有两列存在时才会起作用。在有一列的记录中,你会得到一个伪的“-1列”

#3


7  

@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 awkand gawk).

@jim mcnamara:试着用圆括号来表示NF,即$(NF-1)和$(NF),而不是$NF-1和$NF(在Mac OS X 10.6.8中用于FreeBSD尴尬和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

#4


1  

using gawk exhibits the problem:

使用gawk显示问题:

 gawk '{ print $NF-1, $NF}' filename
1 2
2 3
-1 one
-1 three
# cat filename
1 2
2 3
one
one two three

I just put gawk on Solaris 10 M4000: So, gawk is the cuplrit on the $NF-1 vs. $(NF-1) issue. Next question what does POSIX say? per:

我只是把gawk放在了Solaris 10 M4000上:所以,gawk是$NF-1和$(NF-1)问题的cuplrit。下一个问题,POSIX说什么?/:

http://www.opengroup.org/onlinepubs/009695399/utilities/awk.html

There is no direction one way or the other. Not good. gawk implies subtraction, other awks imply field number or subtraction. hmm.

没有方向,也没有方向。不好的。gawk表示减法,其他的awks表示字段数或减法。嗯。