sort是脚本中常用的排序命令,其可以根据不同的数据类型进行排序,其基本用法如下:
-b: 忽略排序字段或关键字中开头的空格
-c: 检查是否指定文件已经排序好了,不排序.
-d: 在关键字中只考虑[a-zA-Z0-9]字符.
-f: 将关键字中的小写字母折合成大写字母.
-g: 按照通常的数字值顺序作比较,暗含-b
-i: 在关键字中只考虑[\040-\0176]字符.
-k POS1[,POS2]:从关键字POS1开始,*到*POS2结束. 字段数和字符偏移量都从1开始计数(与基于零的+POS格式作比较)
-l: 按照当前环境排序.
-m: 合并已经排序好的文件,不排序.
-M: 按(未知的)<`JAN'<…<`DEC’的顺序比较,暗含-b
-n: 按照字符串的数值顺序比较,暗含-b
-o FILE:将结果写入FILE而不是标准输出.
-r: 颠倒比较的结果.
-s: 通过屏蔽最后的再分类比较来稳定排序.
-t SEP:使用SEP来替代空格的转换non-.
-T DIRECTORY:使用DIRECTORY作为临时文件,而不是$TMPDIR或者/tmp
-u: 如果有-c,则按严格的顺序进行检查; 如果有-m,则只输出相等顺序的第一个.
-z: 以0字节结束行,而不是使用换行符,这是为了找到-print0
uniq: uniq必须与sort结合使用,或者用于已经排序的文件
-c, –count: 在行首显示出现的数目
-d, –repeated: 仅显示 重复行
-D, –all-repeated: 显示 全部 重复行
-f, –skip-fields=N: 不比较 起初的 N 栏
-i, –ignore-case: 比较时 忽略 大小写
-s, –skip-chars=N: 不比较 起初的 N 个 字符
-u, –unique: 仅显示 无重复行
-w, –check-chars=N: 每行中 比较 不超过 N 个 字符
<code> 下面简单介绍其用法: [root@localhost test]# sort a #直接排序输出 1234 1234 fgh zxc [root@localhost test]# sort -r a #逆序输出 zxc fgh 1234 1234 [root@localhost test]# sort -n a #先按字母再按数字排序 fgh zxc 1234 1234 </code>
除非指定了‘-r’参数,否则排序的优先级按下面规则排序
以数字开头的行优先级最高
以小写字母开头的行优先级次之
待排序内容按字典序进行排序
默认情况下,‘sort’命令将带排序内容的每行关键字当作一个字符串进行字典序排序
<code> [root@localhost test]# sort -u a #输出并删除重复的行,与 sort a | uniq 相等 1234 fgh zxc [root@localhost test]# sort -C a #检查是否已经排序 [root@localhost test]# echo $? 1 [root@localhost test]# sort -k 1,1 /etc/passwd #-k+数字:表示按第级列排序 abrt:x:173:173::/etc/abrt:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin apache:x:48:48:Apache:/var/www:/sbin/nologin [root@localhost test]# sort a | uniq -c #显示各行出现的次数 2 1234 1 fgh 1 zxc [root@localhost test]# sort a | uniq -d #找出重复的行 1234 今天在用sort时,发现了一个奇怪的现象,查了半天才弄明白sort的一种特殊的用法,下面为大家解释: info sort `-u' `--unique' Normally, output only the first of a sequence of lines that compare equal. For the `--check' (`-c' or `-C') option, check that no pair of consecutive lines compares equal. This option also disables the default last-resort comparison. The commands `sort -u' and `sort | uniq' are equivalent, but this equivalence does not extend to arbitrary `sort' options. For example, `sort -n -u' inspects only the value of the initial numeric string when checking for uniqueness, whereas `sort -n | uniq' inspects the entire line. *Note uniq invocation::. [root@localhost test]# sort -u -n a #四行变为两行了,参数的意思上面都有 zxc 1234 这种特殊用法是这么理解的,根据上面info sort中的说明 'sort -u' 和 `sort | uniq'等同 但 `sort -n -u' 却不等同 `sort -n | uniq' 根据测试是为数字,若前面是为字符串开头的行,将除第一个行以外的字符串都为0.然后将数字排序输出,若前面航以数字开头,则只给数字排序。(注意0不会输出) [root@localhost test]# cat a a b 0 2 [root@localhost test]# sort -n -u a a 2 [root@localhost test]# cat a 0 2 a 6 b [root@localhost test]# sort -n -u a 0 2 6 </code>