sort Commandsort命令

Sort lines of text files对文本文件的行进行排序

What is sort?什么是sort?

The sort command arranges lines in text files in alphabetical/numerical order. By default, it sorts alphabetically, but you can sort numerically, in reverse order, or by specific columns. It's perfect for organizing lists, logs, or data files.

sort命令按字母/数字顺序排列文本文件中的行。默认情况下,它按字母顺序排序,但你也可以按数字、反向或特定列排序。非常适合组织列表、日志或数据文件。

Basic Usage基本用法

$ sort names.txt
# Sort alphabetically (default)
$ sort -n numbers.txt
# Sort numerically (2 before 10)
$ sort -r names.txt
# Sort in reverse order
$ sort names.txt
# 按字母顺序排序(默认)
$ sort -n numbers.txt
# 按数字排序(2在10之前)
$ sort -r names.txt
# 反向排序

Common Options常用选项

Option选项 Full Name完整名称 Description描述 Example示例
-r reverse反向 Sort in reverse order反向排序 sort -r names.txt
-n numeric-sort数字排序 Compare numerically按数字比较 sort -n numbers.txt
-u unique唯一 Output only unique lines仅输出唯一的行 sort -u items.txt
-k N key Sort by Nth field按第N个字段排序 sort -k2 -t: data.txt
-t C field-separator字段分隔符 Use C as delimiter使用C作为分隔符 sort -t, -k2 csv.txt
-f ignore-case忽略大小写 Fold lower case to upper将小写折叠为大写 sort -f names.txt

Practical Scenarios实际场景

Sort CSV by Column按列排序CSV

$ sort -t, -k2 -n scores.csv
# Sort CSV by 2nd column numerically
$ sort -t, -k2 -n scores.csv
# 按第2列数字排序CSV

Sort and Remove Duplicates排序并删除重复项

$ sort -u unsorted.txt > sorted-unique.txt
# Sort and remove duplicates in one go
$ sort -u unsorted.txt > sorted-unique.txt
# 一次性排序并删除重复项

Memory Tricks记忆技巧

🔤 "sort" = sort alphabetically by default - Like organizing a dictionary!

🔤 "sort" = 默认按字母排序 - 像组织字典一样!

🔢 -n = Numeric sort - Important: 2 < 10 (not "2" > "10")

🔢 -n = Numeric sort(数字排序) - 重要:2 < 10(不是"2" > "10")

🔄 -r = Reverse - Flip the sort order

🔄 -r = Reverse(反向) - 翻转排序顺序

✨ -u = Unique - Remove duplicates too

✨ -u = Unique(唯一) - 同时删除重复项