Chinaunix

标题: 【关于sort命令的一点疑问以及理解】 [打印本页]

作者: Diao_Cow    时间: 2012-08-12 13:24
标题: 【关于sort命令的一点疑问以及理解】
本帖最后由 Diao_Cow 于 2012-08-12 14:14 编辑

最近学习了sort命令,一开始觉得很容易上手,但是细挖一下,发现很多细节都很迷糊,网上也查了些资料,但是发现大家写的都差不多,于是自己info sort去看指南,并且做了些实验,现在发个总结上来,不知自己理解是否正确,还望各位前辈指点:

自己的主要迷糊点在于,默认是按行还是按列比较,默认分隔符是什么,怎么分隔的?


`-t SEPARATOR'
`--field-separator=SEPARATOR'
     Use character SEPARATOR as the field separator when finding the
     sort keys in each line.  By default, fields are separated by the
     empty string between a non-blank character and a blank character.
     That is, given the input line ` foo bar', `sort' breaks it into
     fields ` foo' and ` bar'.  The field separator is not considered
     to be part of either the field preceding or the field following,
     so with `sort -t " "' the same input line has three fields: an
     empty field, `foo', and `bar'.  However, fields that extend to the
     end of the line, as `-k 2', or fields consisting of a range, as
     `-k 2,3', retain the field separators present between the
     endpoints of the range.
         
If no key fields are specified, `sort' uses a default key of
the entire line


从上面看出:
1.如果不指定-k选项,默认是按行排序的;
2.如果指定了-k选项,但没有指定分隔符,则默认使用empty string分隔符;
3.默认分隔符(empty string)和用户指定分隔符分隔域的最大不同是:采用用户指定分隔符分隔域后,被分隔的域不会包含分隔符;

我们看几个例子:

cat test
a b c d
空格a b c d

cat test | sort
空格a b c d
a b c d

由于没有指定-k,默认是按行排序,从第一个字符开始比较,由于空格的ascii码值小于字母a,所以排在前面;
cat test
a b c d
a  b c d
cat test |sort -k2
a  b c d
a b c d

按照第二个域排序,第二个域分别是什么呢? '空格b' , '空格空格b',当比较到第2个字符的时候,由于空格的ascii码值小于字母b,所以a空格空格b c d排在前面

再看一个例子:
cat test
aohu 103240 2200
sohu 10310 21200
cat test | sort -k2.2,2.4
aohu 103240 2200
sohu 10310 21200

发现没,没有按照我们预想的排序;
由于没有指定分隔符,默认使用emptyString,所以第二个域实际上是:'空格103240'和'空格10310',所以从第2个到第4个字符都是相同的,那么如何解决这个问题呢?只要自己指定空格字符就行了

cat test | sort -t' ' -k 2.2,2.4
sohu 10310 21200
aohu 103240 2200

作者: blackold    时间: 2012-08-12 15:09
赞!!!


作者: winway1988    时间: 2012-08-12 16:44
赞!!!
+1
作者: zooyo    时间: 2012-08-12 22:59
提示: 作者被禁止或删除 内容自动屏蔽
作者: dn833    时间: 2012-08-13 00:17
空格的道道~多谢LZ的sort分享
作者: personball    时间: 2012-08-13 08:46
不错,谢谢分享
作者: waker    时间: 2012-08-13 08:56
不是有-b选项么?
作者: rdcwayx    时间: 2012-08-13 11:32
cat test | sort -t' ' -k 2.2,2.4  这条命令倒是没错,但是通常可以用下面的命令避开异议。
  1. sort -k2n test
复制代码

作者: Diao_Cow    时间: 2012-08-13 16:51
waker 发表于 2012-08-13 08:56
不是有-b选项么?



`-b'
`--ignore-leading-blanks'
     Ignore leading blanks when finding sort keys in each line.  The
     `LC_CTYPE' locale determines character types.


学习了!




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2