关于sort工具-k选项中字母排序参数的详细解释请求
sort -k Option Flags ([bdfgiMhnRrV]) Let's walk through each single-letter flag you can pair with the -k (key) option in sort. These flags let you override global sort settings only for the specific key you're defining—super handy when you need different sorting rules for different columns or fields in your data.
b: Ignore leading blanks (whitespace) when comparing the key. If your data has fields with leading spaces, this ensuressortdoesn’t count those spaces as part of the value for that key.
Example: Using-k1,1bwill sort123and45as45before123(since it skips the leading spaces).d: Use dictionary order—only consider letters, digits, and whitespace. Special characters (like!@#$) get ignored during the key comparison. Ideal for sorting text where punctuation doesn’t matter.f: Fold lowercase to uppercase (case-insensitive sorting) for the key. SoappleandApplewill be treated as identical for this key, even if your global sort settings are case-sensitive.g: Use general numeric value sorting. This handles floating-point numbers and scientific notation (like1.2e3) correctly—more flexible than the integer-focused-nflag.i: Ignore non-printable characters when comparing the key. If your data has hidden control characters, this flag makessortskip them for the specific key you’re configuring.M: Sort by month name. Recognizes three-letter abbreviations (Jan, Feb, ..., Dec) and full month names (January, February) if your system locale supports it. Perfect for date columns that use month names instead of numbers.h: Sort human-readable numbers (like1K,2M,3Gfor kilobytes/megabytes/gigabytes). It parses the suffixes and sorts values numerically, so100Kcomes before2M.n: Use numeric value sorting (integer-focused). Treats the key as an integer, so10comes after2(unlike default lexicographical sort where10would come before2).R: Sort the key randomly (based on the key’s hash). Rows with identical keys stay grouped, but their order relative to other groups is randomized—different from a full shuffle of all rows.r: Reverse the sort order for this key. If your global sort is ascending,-k2,2rwill make the second key sort in descending order instead.V: Version sort. This sorts alphanumeric strings in a version-aware way—for example,v1.9comes beforev1.10, which doesn’t happen with default lexicographical sort.
Quick Example of Combined Usage
Suppose you have a file data.txt with:
apple 100K Jan Banana 2M Feb cherry 50K Dec
Running this command:
sort -k2,2hr -k3,3M data.txt
Will:
- Sort the second key (size column) in human-readable reverse order (so
2Mcomes first, then100K, then50K) - For rows with the same size, sort by the third key (month) in month order (Jan before Feb before Dec)
内容的提问来源于stack exchange,提问作者user276072

