在一行的最后一个字段上排序 [英] Sorting on the last field of a line

查看:91
本文介绍了在一行的最后一个字段上排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对行列表进行排序(在每行的最后一个字段上排序)的最简单方法是什么?每行可能具有可变数量的字段.

What is the simplest way to sort a list of lines, sorting on the last field of each line? Each line may have a variable number of fields.

类似

sort -k -1

是我想要的,但是sort(1)不需要负数来从头开始而不是从头开始选择字段.

is what I want, but sort(1) does not take negative numbers to select fields from the end instead of the start.

我也希望能够选择字段定界符.

I'd also like to be able to choose the field delimiter too.

为问题增加一些特殊性:我要排序的列表是路径名列表.路径名可以是任意深度,因此字段数是可变的.我想对文件名组件进行排序.

To add some specificity to the question: The list I want to sort is a list of pathnames. The pathnames may be of arbitrary depth hence the variable number of fields. I want to sort on the filename component.

此附加信息可能会更改操作行以提取最后一个字段的方式(可以使用basename(1)),但不会更改排序要求.

This additional information may change how one manipulates the line to extract the last field (basename(1) may be used), but does not change sorting requirements.

例如

/a/b/c/10-foo
/a/b/c/20-bar
/a/b/c/50-baz
/a/d/30-bob
/a/e/f/g/h/01-do-this-first
/a/e/f/g/h/99-local

我希望此列表按文件名排序,所有文件名均以数字开头,该数字指示应读取文件的顺序.

I want this list sorted on the filenames, which all start with numbers indicating the order the files should be read.

我在下面添加了我的答案,这是我目前的做法.我曾希望有一种更简单的方法-也许是另一种排序实用程序-也许不需要操纵数据.

I've added my answer below which is how I am currently doing it. I had hoped there was a simpler way - maybe a different sort utility - perhaps without needing to manipulate the data.

推荐答案

以下是Perl命令行(请注意,您的shell可能要求您转义$ s):

Here's a Perl command line (note that your shell may require you to escape the $s):

perl -e "print sort {(split '/', $a)[-1] <=> (split '/', $b)[-1]} <>"

只需将列表通过管道传输到其中,或者如果列表在文件中,则将文件名放在命令行末尾.

Just pipe the list into it or, if the list is in a file, put the filename at the end of the command line.

请注意,此脚本实际上并不会更改数据,因此您不必在意使用的分度数.

Note that this script does not actually change the data, so you don't have to be careful about what delimeter you use.

以下是示例输出:


>perl -e "print sort {(split '/', $a)[-1] <=> (split '/', $b)[-1]} " files.txt
/a/e/f/g/h/01-do-this-first
/a/b/c/10-foo
/a/b/c/20-bar
/a/d/30-bob
/a/b/c/50-baz
/a/e/f/g/h/99-local

这篇关于在一行的最后一个字段上排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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