首页·终端命令

sort

文本处理

用法

sort -k 2 -n [file]

给行排序;不加 -n 就按文本比较,于是 10 排在 9 前面,而顺序由 locale 决定,除非在前面加 LC_ALL=C。

常用选项

选项含义
-nCompare as numbers, not as text
-hCompare human sizes such as 2K and 1G
-rReverse the order
-kSort by a field, as in -k2
-tSet the field separator
-uDrop duplicate lines
-fIgnore case
-oWrite the result to a file, even back onto the input

示例

du -sh * | sort -h

Biggest directory last.

sort -t, -k2 -n data.csv

Numeric sort on the second column.

sort -u names.txt

Sorted, with duplicates gone.

它们本来就是用管道串起来用的。串三条往往比让一条命令做完所有事更短。

怎么看

  • 方括号 [ ] 表示这部分可以不写。
  • 省略号 … 表示可以写多个。
  • 选项区分大小写——有些命令里 -r 和 -R 不是一回事。

常见问题

Q. sort 是做什么的?

给行排序;不加 -n 就按文本比较,于是 10 排在 9 前面,而顺序由 locale 决定,除非在前面加 LC_ALL=C。

Q. 怎么写?

sort -k 2 -n [file] —— 方括号表示可以省略的部分。

Q. 值得记的选项有几个?

这里列了 8 个,完整列表在 man sort。这条命令属于文本处理。

相关命令

man 手册: man sort