You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用sort命令实现小写优先的姓名字典序排序?

Absolutely! You can use sort to meet this requirement

Your core need is to sort names lexicographically but with lowercase-starting names appearing before uppercase-starting ones. This essentially means we need to first sort by case-insensitive lex order, then prioritize entries with lowercase letters over all-uppercase ones when they're the same name.

How to adjust your command

The sort command has key options to make this work:

  • -f/--ignore-case: Compares strings without considering case, so Ana, ANA, and Any will first be grouped by their lowercase equivalents (ana, ana, any).
  • -k/--key: Lets us define multi-level sorting rules. We'll use two keys here:
    1. First key: Sort case-insensitively on the name portion to get the overall lex order.
    2. Second key: Reverse-sort on the original string, so entries with lowercase characters (which have higher ASCII values) come before all-uppercase versions.

Here's the modified version of your existing command:

cut -d";" -f2-3 "$1" | paste - "$1" | sort -k1,1f -k1,1r | cut -f2- >> sorted.txt

Testing this with your example

Let's test with your sample inputs (Any, ANA, Ana):

  1. The first case-insensitive key groups ANA and Ana together (since their lowercase is ana), and Any is in its own group (any). Since ana comes before any lex order, the ana group is first.
  2. The reverse-sort key compares the original strings: Ana has a higher ASCII value than ANA (because n (110) > N (78)), so reverse-sorting puts Ana before ANA.
  3. Finally, Any follows the ana group.

The final sorted order will be: Ana, ANA, Any—which I think is the correct result you're aiming for (it looks like your example might have had a small typo in the desired order 😊).

If you meant "all lowercase-starting names first, regardless of lex order"

If your actual goal is to put every name starting with a lowercase letter before every name starting with an uppercase letter (separate groups, then sorted within each), use this command instead:

cut -d";" -f2-3 "$1" | paste - "$1" | sort -k1.1,1.1r -k1,1 | cut -f2- >> sorted.txt

The -k1.1,1.1r part reverses the sort of the first character only—since lowercase letters have higher ASCII values, reversing puts them first. Then -k1,1 sorts each group lexicographically.

内容的提问来源于stack exchange,提问作者Freddy19

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:37:42