在我正在重新格式化的文件中,我想将最后一列作为第一列,并让其余列保持不变。我可以在 python 中轻松做到这一点,但我想今晚我会学习一些 awk。
这是一个例子:
(前)
polk_describes:1 diatribe_that:1 #label#:negative
(后)
#label#:negative polk_describes:1 diatribe_that:1
但是,有很多超过 3 列。事实上,列数会有所不同。
谢谢,
SetJmp
您可以对字段进行分配,从而清除它们:
awk '{ lastfield = $NF; $NF = ""; print lastfield " " $0 }'
这是一个选项:
% echo 'polk_describes:1 diatribe_that:1 #label#:negative' | \
awk '{ print $NF " " substr($0, 1, length($0) - length($NF)) }'
#label#:negative polk_describes:1 diatribe_that:1
您想打印 $0 但删除最后几个字段吗?就像您可以分配给一个字段以自动更改 $0 一样,您可以分配给 NF 以删除最后一个字段。
{ NF = NF - 2 ; print "All but the last two: " $) }
print $(NF), $1, $2, $3, $4 # etc. to the max number of columns
关于列数,也可以写在更优雅和更精确的循环中。(另请参阅这篇文章中 Nicholas Riley 的技巧,将最后一个字段从 $0 中截断并立即打印)。