Linux shell 根据第二列对文件进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4262650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:54:15  来源:igfitidea点击:

Linux shell sort file according to the second column?

linuxshell

提问by Rami Jarrar

I have a file like this:

我有一个这样的文件:

FirstName, FamilyName, Address, PhoneNumber

How can I sort it by FamilyName?

如何按 FamilyName 对其进行排序?

采纳答案by John Kugelman

If this is UNIX:

如果这是 UNIX:

sort -k 2 file.txt

You can use multiple -kflags to sort on more than one column. For example, to sort by family name then first name as a tie breaker:

您可以使用多个-k标志对多列进行排序。例如,要按姓氏排序,然后按名字排序:

sort -k 2,2 -k 1,1 file.txt

Relevant options from "man sort":

“man sort”的相关选项:

-k, --key=POS1[,POS2]

start a key at POS1, end it at POS2 (origin 1)

POS is F[.C][OPTS], where F is the field number and C the character position in the field. OPTS is one or more single-letter ordering options, which override global ordering options for that key. If no key is given, use the entire line as the key.

-t, --field-separator=SEP

use SEP instead of non-blank to blank transition

-k, --key=POS1[,POS2]

在 POS1 开始一个键,在 POS2 结束它(原点 1)

POS 是 F[.C][OPTS],其中 F 是字段编号,C 是字段中的字符位置。OPTS 是一个或多个单字母排序选项,它会覆盖该键的全局排序选项。如果没有给出键,则使用整行作为键。

-t, --field-separator=SEP

使用 SEP 而不是非空白到空白过渡

回答by Cian

To sort by second field only (thus where second fields match, those lines with matches remain in the order they are in the original without sorting on other fields) :

仅按第二个字段排序(因此在第二个字段匹配的情况下,那些匹配的行保持它们在原始字段中的顺序,而不对其他字段进行排序):

sort -k 2,2 -s orig_file > sorted_file

回答by Dheeraj Kumar

sort -nk2 file.txt

sort -nk2 file.txt

Accordingly you can change column number.

因此,您可以更改列号。

回答by netskink

FWIW, here is a sort method for showing which processes are using the most virt memory.

FWIW,这是一种排序方法,用于显示哪些进程使用了​​最多的 virt 内存。

memstat | sort -k 1 -t':' -g -r | less

Sort options are set to first column, using : as column seperator, numeric sort and sort in reverse.

排序选项设置为第一列,使用 : 作为列分隔符,数字排序和反向排序。