使用bash对数据进行排序水平 [英] Using bash to sort data horizontally

查看:116
本文介绍了使用bash对数据进行排序水平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个完整的数据文件中列

I have a file full of data in columns

sarah mark john
10    20   5
x     y    z 

我要的数据,因此列保持不变,但排序第二行是为了提高,所以它看起来是这样的:

I want to sort the data so the columns stay intact but the second row is in increasing order so it looks like this:

john sarah mark
5    10    20 
z    x     y 

我一直在寻找的那种命令,但只能够找到垂直分拣,不是水平。我很高兴地使用任何工具,任何帮助是AP preciated。
谢谢!

I've been looking at the sort command but have only been able to find vertical sorting, not horizontal. I'm happy to use any tool, any help is appreciated. Thank you!

推荐答案

让我们创建一个函数来转文件(让行变为列,和列变为行):

Let's create a function to transpose a file (make rows become columns, and columns become rows):

transpose () {
  awk '{for (i=1; i<=NF; i++) a[i,NR]=$i; max=(max<NF?NF:max)}
        END {for (i=1; i<=max; i++)
              {for (j=1; j<=NR; j++) 
                  printf "%s%s", a[i,j], (j<NR?OFS:ORS)
              }
        }'
}

这只是所有的数据加载到一个二维数组 A [行,列] ,然后打印回为 A [列,行] ,使之转置给定的输入。该包装转(){} 用于其存储为一个bash的功能。你只需要复制粘贴到你的shell(或〜/ .bashrc中如果你希望它是一个永久性的功能,可以打开一个会话的任​​何时间)。

This just loads all the data into a bidimensional array a[line,column] and then prints it back as a[column,line], so that it transposes the given input. The wrapper transpose () { } is used to store it as a bash function. You just need to copy paste it in your shell (or in ~/.bashrc if you want it to be a permanent function, available any time you open a session).

然后,通过使用它,我们可以很容易地通过解决问题排序-n -k2 :数字排序基于列2.然后,转回来

Then, by using it, we can easily solve the problem by using sort -n -k2: sort numerically based on column 2. Then, transpose back.

$ cat a | transpose | sort -n -k2 | transpose
john sarah mark
5 10 20
z x y

如果你想拥有一个漂亮的格式最终输出,只是管是这样的:

$ cat a | transpose | sort -n -k2 | transpose | column -t
john  sarah  mark
5     10     20
z     x      y

一步一步:

$ cat a | transpose 
sarah 10 x
mark 20 y
john 5 z
$ cat a | transpose | sort -n -k2
john 5 z
sarah 10 x
mark 20 y
$ cat a | transpose | sort -n -k2 | transpose 
john sarah mark
5 10 20
z x y

这篇关于使用bash对数据进行排序水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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