k 参数在排序函数(Linux Bash Scripting)中有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17478511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does the k parameter do in the sort function (Linux Bash Scripting)?
提问by user2316667
From Linux manual: sort via a key; KEYDEF gives location and type.
来自 Linux 手册:通过键排序;KEYDEF 给出位置和类型。
I have no idea what that means but I saw it being used like this:
我不知道这意味着什么,但我看到它是这样使用的:
cut -f 2 *ptt | tail -n +4 | sort | uniq -c | sort -k1 -rn
And then again like this:
然后又是这样:
ls -1 *\.flv | sort -n -k1.2
回答by perreal
KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a field number and C a character position in the field; both are origin 1, and the stop position defaults to the line's end. If neither -t nor -b is in effect, characters in a field are counted from the beginning of the preceding whitespace. OPTS is one or more single-letter ordering options [bdfgiMhnRrV], which override global ordering options for that key. If no key is given, use the entire line as the key.
KEYDEF 为 F[.C][OPTS][,F[.C][OPTS]] 开始和停止位置,其中 F 是字段编号,C 是字段中的字符位置;两者都是原点 1,停止位置默认为线的末端。如果 -t 和 -b 均无效,则字段中的字符从前一个空格的开头开始计数。OPTS 是一个或多个单字母排序选项 [bdfgiMhnRrV],它会覆盖该键的全局排序选项。如果没有给出键,则使用整行作为键。
An example input file:
示例输入文件:
123 233
214 176
341 325
sort on the first field:
在第一个字段上排序:
sort -t' ' -k1 input
Gives:
给出:
123 233
214 176
341 325
The second field:
第二个字段:
sort -t' ' -k2 input
Gives:
给出:
214 176
123 233
341 325
Second and third digits of the first field:
第一个字段的第二个和第三个数字:
sort -t' ' -k1.2 input
Gives:
给出:
214 176
123 233
341 325
Last digit of the second field:
第二个字段的最后一位数字:
sort -t' ' -k2.3 input
Gives:
给出:
123 233
341 325
214 176
回答by duskwuff -inactive-
In less words than the manual page: it specifies what "column" the file is sorted by. If the column number contains a period, the value past the period is used as an offset within the field. For instance, -k1.2sorts by the second character of the first column.
用比手册页更少的话:它指定了文件排序的“列”。如果列号包含句点,则使用句点之后的值作为字段内的偏移量。例如,-k1.2按第一列的第二个字符排序。
Columns are normally delimited by tab characters, but you can change that with -t. For instance, -t,would use columns delimited by commas (e.g, a CSV file).
列通常由制表符分隔,但您可以使用-t. 例如,-t,将使用以逗号分隔的列(例如,CSV 文件)。

