我怎样才能用awk通过列的最后一个值的列进行排序? [英] How can I use awk to sort columns by the last value of a column?

查看:635
本文介绍了我怎样才能用awk通过列的最后一个值的列进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个文件(数百行和列)。

  1 2 3
4 5 6
7 9 88

和我想重新排列基础上最后一行值的列(或特定行的值)

  1 3 2
4 6 5
7 9 88

我如何使用AWK(或其他方式)来完成这个任务?
预先感谢您的帮助。

修改:我想感谢大家,并道歉,如果我不太清楚。
我想这样做的是:


  • 走线(例如最后一个);

  • 使用所选行的排序的值到derermine顺序重新排序矩阵中的列。

所以,最后一行是 7 88 9 ,它分类为 7 9 88 ,那么三列已到的方式,使得在此情况下,最后两列互换进行重新排序


一个四柱更通用的例子的基础上,最后一行一次:

输入:

  1 2 3 4
4 5 6 7
7 88.0 9 -3

输出:

  4 1 3 2
 7 4 6 5
-3 7 9 88.0


解决方案

下面是一个简单的,肮脏的和可改进的解决方案:(编辑,因为OP澄清,数字浮点)

  $猫TEST.DAT
1 2 3
4 5 6
0.07 0.88 -.09
$ awk的{$打印(printf的'$%D%.0s \\ n'\\
                  $(i = 0;在$ X(尾-n1 TEST.DAT); DO
                           回声$((++ i))的$ X
                         做|
                  排序-k2g)|粘贴-sd,)}TEST.DAT
3 1 2
6 4 5
-.09 0.07 0.88

要看看会发生什么在那里(或至少它的一部分):

  $回声{$打印(printf的'$%D%.0s \\ n'\\
                      $(i = 0;在$ X(尾-n1 TEST.DAT); DO
                               回声$((++ i))的$ X
                             做|
                      排序-k2g)|粘贴-sd,)}TEST.DAT
{打印$ 3,$ 1,$ 2} TEST.DAT

要使它成为一个独断专行的工作,取代尾-n1 尾-n + $ L |头-n1

I have a file like this (with hundreds of lines and columns)

1  2 3
4  5 6
7 88 9

and I would like to re-order columns basing on the last line values (or a specific line values)

1 3 2
4 6 5
7 9 88

How can I use awk (or other) to accomplish this task? Thank you in advance for your help

EDIT: I would like to thank everybody and to apologize if I wasn't enough clear. What I would like to do is:

  • take a line (for example the last one);
  • reorder the columns of the matrix using the sorted values of the chosen line to derermine the order.

So, the last line is 7 88 9, which sorted is 7 9 88, then the three columns have to be reordered in a way such that, in this case, the last two columns are swapped.


A four-column more generic example, based on the last line again:

Input:

1    2 3  4
4    5 6  7
7 88.0 9 -3

Output:

 4 1 3 2
 7 4 6 5
-3 7 9 88.0

解决方案

Here's a quick, dirty and improvable solution: (edited because OP clarified that numbers are floating point).

$ cat test.dat
1 2 3
4 5 6
.07 .88 -.09
$ awk "{print $(printf '$%d%.0s\n' \
                  $(i=0; for x in $(tail -n1 test.dat); do
                           echo $((++i)) $x
                         done |
                  sort -k2g) | paste -sd,)}" test.dat
3 1 2
6 4 5
-.09 .07 .88

To see what's going on there (or at least part of it):

$ echo "{print $(printf '$%d%.0s\n' \
                      $(i=0; for x in $(tail -n1 test.dat); do
                               echo $((++i)) $x
                             done |
                      sort -k2g) | paste -sd,)}" test.dat
{print $3,$1,$2} test.dat

To make it work for an arbitrary line, replace tail -n1 with tail -n+$L|head -n1

这篇关于我怎样才能用awk通过列的最后一个值的列进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆