如何使用sort命令实现小写优先的姓名字典序排序?
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, soAna,ANA, andAnywill 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:- First key: Sort case-insensitively on the name portion to get the overall lex order.
- 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):
- The first case-insensitive key groups
ANAandAnatogether (since their lowercase isana), andAnyis in its own group (any). Sinceanacomes beforeanylex order, theanagroup is first. - The reverse-sort key compares the original strings:
Anahas a higher ASCII value thanANA(becausen(110) >N(78)), so reverse-sorting putsAnabeforeANA. - Finally,
Anyfollows theanagroup.
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

