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

查看:35
本文介绍了使用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 

我一直在查看排序命令,但只能找到垂直排序,而不是水平排序.我很高兴使用任何工具,任何帮助表示赞赏.谢谢!

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[line,column],然后将其打印回a[column,line],以便它转置给定的输入.包装器 transpose () { } 用于将其存储为 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).

然后,通过使用它,我们可以使用sort -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

如果你想要一个漂亮的格式作为最终输出,只需像这样管道到column:

In case you want to have a nice format as final output, just pipe to column like this:

$ 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天全站免登陆