我只想要最后两栏。
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 column1"
您可以使用变量 NF,它被设置为输入记录中的字段总数:
NF
awk '{print $(NF-1),"\t",$NF}' file
这里假设您至少有两个字段。
using gawk exhibits the problem:
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? 按:
http://www.opengroup.org/onlinepubs/009695399/utilities/awk.html
没有任何方向。情况不妙。Gawk 表示减法,其他 awk 表示字段数或减法。嗯。
@ jim mcnamara: 尝试在 NF左右使用括号,即 $(NF-1)和 $(NF),而不是 $NF-1和 $NF(可以在 Mac OS X 10.6.8上使用,适用于 FreeBSD awk和 gawk)。
$(NF-1)
$(NF)
$NF-1
$NF
awk
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
试试这个
$ cat /tmp/topfs.txt /dev/sda2 xfs 32G 10G 22G 32% / awk print last column $ cat /tmp/topfs.txt | awk '{print $NF}' awk print before last column $ cat /tmp/topfs.txt | awk '{print $(NF-1)}' 32% awk - print last two columns $ cat /tmp/topfs.txt | awk '{print $(NF-1), $NF}' 32% /
Please try this out to take into account all possible scenarios:
awk '{print $(NF-1)"\t"$NF}' file
或者
awk 'BEGIN{OFS="\t"}' file
awk '{print $(NF-1), $NF} {print $(NF-1), $NF}' file