Shell脚本攻略学习笔记十一之sort命令

1.sort命令

The sort command accepts input as filenames,as well as from stdin.

1.1参数详解
-o, --output=FILE
write result to FILE instead of standard output

-n, --numeric-sort
compare according to string numerical value

-r, --reverse
reverse the result of comparisons

-m, --merge
merge already sorted files; do not sort

-b, --ignore-leading-blanks
ignore leading blanks【忽略前导空格】

-d, --dictionary-order
consider only blanks and alphanumeric characters

-u, --unique
with -c, check for strict ordering; without -c, output only the first of an equal run
【不太理解这个参数的使用】
1.2命令实战
[root@server4 shells]# ./isSorted.sh sorted.txt 
sorted
[root@server4 shells]# cat isSorted.sh
#!/bin/bash
filename=$1
sort -C ${filename}
if [ $? -eq 0 ]
then
echo sorted;
else
echo unsorted;
fi

We exploit the fact that sort returns an exit code ($?) of 0 if the file is sorted and nonzero otherwise.

Sorting according to the keys or columns

  • -nr means ​​numeric​​​ and ​​reverse​
[root@server4 shells]# sort -nrk 1 data.txt 
4 linux 1000
3 bsd 1000
2 winxp 4000
1 mac 2000
[root@server4 shells]# sort -nrk 3 data.txt
2 winxp 4000
1 mac 2000
4 linux 1000
3 bsd 1000

2.uniq命令

  • 使用​​uniq​​​命令将​​sorted.txt​​​中的重复内容删除
    先查看sorted.txt文件中的内容
[root@server4 shells]# cat sorted.txt 

1
2
2
21
3
4
42
5
5
9
  • 去除文件中重复的数据
[root@server4 shells]# uniq sorted.txt 

1
2
21
3
4
42
5
9
  • -u –unique
    only print unique lines【仅仅打印唯一的行(也就是说如果有重复的行,则不会打印)】
[root@server4 shells]# uniq -u sorted.txt 

1
21
3
4
42
9
  • -c, –count
    prefix lines by the number of occurrences【出现的次数作为前缀】
[root@server4 shells]# uniq -c sorted.txt 
1
1 1
2 2
1 21
1 3
1 4
1 42
2 5
1 9
[root@server4 shells]# uniq -d sorted.txt
2
5