这只是一个小问题,但是假攻略太多了,所有发出真正的答案。
数据如下:
ba 11 a
ab 1 b
aa 1 c
ba 3 d
要求:先按第一列排序,如果重复,再按第2列以数字方式排序
先看一下非常容易百度出来的错误答案:
第一条: 并列参数, 也就是 sort -k1 -k2n file,输出如下,错误:
aa 1 c
ab 1 b
ba 11 a
ba 3 d
第二条: 同上,后面发现了问题,但是给出了错误的解释
第三条: 答案是对的,但没解释,sort -k1,1 -k2,2n file,输出如下:
aa 1 c
ab 1 b
ba 3 d
ba 11 a
再后面对错都有了。所以请记住要长记性,此处省略……
正解及原因:
答案是:sort -k1,1 -k2,2n file
原因很简单,只要man sort一下看一下说明就行了:
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.
再强调一遍, -k2 并不是按第2列排序,而是第2列开始,一个到行尾所有内容拿出来排序。