[英]Unix, Sort by number
I want to sort my file by decreasing number of the second column, but not changing the place of the header. 我想通过减少第二列的数量对文件进行排序,但不更改标题的位置。 Currently it is like this in a csv file that has two columns like this: 当前,在csv文件中就像这样,它具有两列,如下所示:
Person Age
Sarah 15
Robert 23
Emma 31
Bob 9
I want it to be like this: 我希望它是这样的:
Person Age
Emma 31
Robert 23
Sarah 15
Bob 9
Please help a beginner in Unix. 请帮助Unix初学者。
Read http://man7.org/linux/man-pages/man1/sort.1.html to learn about the sort
command on UNIX/Linux. 阅读http://man7.org/linux/man-pages/man1/sort.1.html,以了解UNIX / Linux上的sort
命令。 That's how I and everyone else learned. 这就是我和其他所有人所学到的。
$ sort --key 2 --reverse --numeric-sort myfile > mysortedfile
The only problem is that this sorts the line with "Person Age" as if it had the numeric value of zero, and moves it to the last line of the file. 唯一的问题是,这会将“ Person Age”(行人年龄)的行排序为数字值零,然后将其移动到文件的最后一行。 You then have to move that line after sorting the file. 然后,您必须在对文件进行排序后移动该行。
This will do the trick except remove blank lines. 除了删除空行,这将达到目的。
sed -n '1 ! sed -n'1! p' sortme.txt | p'sortme.txt | sort --key 2 --reverse --numeric-sort | sort --key 2 --reverse --numeric-sort | sed '1 i\\Person\\tAge' > sorted.txt sed'1 i \\ Person \\ tAge'> sorted.txt
~Pat 〜帕特
To solve the "header in front" problem as outlined in Bills answer, you could use awk
in addition to sort
: 要解决Bills答案中概述的“最前面的标题”问题,除了sort
之外,还可以使用awk
:
awk 'NR==1 {print ; next } { print | "sort -n -r -k2" }' yourfile > sorted_file
NR==1
applies only for the first line: it is printed 条件NR==1
仅适用于第一行:打印 sort
command (you could do the sorting in awk
itself, but that would be a bit longer ) 所有其他行都通过管道传递给sort
命令(您可以在awk
本身中进行排序,但这会更长一些)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.