shell sort命令:如何按最后一列排序(列数不确定)? [英] shell sort command : How to sort by the last column (the number of columns is uncertain)?

查看:2021
本文介绍了shell sort命令:如何按最后一列排序(列数不确定)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果数据如下所示:

a,b,3
c,d,e,f,2
g,1

我要按最后一列排序.结果应该是:

I want sort by the last column. the result should be:

g,1
c,d,e,f,2
a,b,3

推荐答案

如果最后一个字段是一位数字

if the last field is single digit

$ rev file | sort | rev

您可能需要添加-t, -n来对数字顺序进行排序,但不要用一位数字.

you may need to add -t, -n to sort for numerical ordering but single digits it doesn't matter.

或者,对于通常使用awk

$ awk -F, '{a[$NF]=$0} END{n=asorti(a,d); for(k=1;k<=n;k++) print a[d[k]]}' file

g,1
c,d,e,f,2
a,b,3

如果最后一个字段不是唯一的,这将失败.使用装饰/分类/取消装饰惯用语,您可以改写(如发现自己一样)

This will fail if the last field is not unique. Using decorate/sort/undecorate idiom you can write instead (as you found yourself)

$ awk -F, '{print $NF FS $0}' file | sort -n | cut -d, -f2-

在键和记录之间使用字段定界符比较安全,因为您要确保FS不会出现在键本身中.

it's safer to use the field delimiter between the key and the record since you want to ensure the FS doesn't appear in the key itself.

这篇关于shell sort命令:如何按最后一列排序(列数不确定)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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