目录
1.sort 排序命令语法及参数
很多情况下都需要对无序的数据进行排序,这时就要用到sort排序了。
语法
sort [-bcdfimMnr][-o<输出文件>][-t<分隔字符>][+<起始栏位>-<结束栏位>][--help][--verison][文件][-k field1[,field2]]
参数说明:
- -b 忽略每行前面开始出的空格字符。
- -c 检查文件是否已经按照顺序排序。
- -d 排序时,处理英文字母、数字及空格字符外,忽略其他的字符。
- -f 排序时,将小写字母视为大写字母。
- -i 排序时,除了040至176之间的ASCII字符外,忽略其他的字符。
- -m 将几个排序好的文件进行合并。
- -M 将前面3个字母依照月份的缩写进行排序。
- -n 依照数值的大小排序。
- -u 意味着是唯一的(unique),输出的结果是去完重了的。
- -o<输出文件> 将排序后的结果存入指定的文件。
- -r 以相反的顺序来排序。
- -t<分隔字符> 指定排序时所用的栏位分隔字符。
- +<起始栏位>-<结束栏位> 以指定的栏位来排序,范围由起始栏位到结束栏位的前一栏位。
- --help 显示帮助。
- --version 显示版本信息。
- [-k field1[,field2]] 按指定的列进行排序。
2.sort命令用法演示
在使用 sort 命令以默认的式对文件的行进行排序,使用的命令如下:
[root@xiaopeng ~]# sort testfile
sort 命令将以默认的方式将文本文件的第一列以 ASCII 码的次序排列,并将结果输出到标准输出。
使用 cat 命令显示 testfile 文件可知其原有的排序如下:
[root@xiaopeng ~]# cat testfile # testfile文件原有排序
test 30
Hello 95
Linux 85
使用 sort 命令重排后的结果如下:
[root@xiaopeng ~]# sort testfile # 重排结果
Hello 95
Linux 85
test 30
使用 -k 参数设置对第二列的值进行重排,结果如下:
[root@xiaopeng ~]# sort testfile -k 2
test 30
Linux 85
Hello 95
3.uniq 去重命令语法及参数
uniq命令是用来取消重复行的命令,其实和sort -u选项是一样的。
用法:uniq [选项]... [文件]
从输入文件或者标准输入中筛选相邻的匹配行并写入到输出文件或标准输出。
不附加任何选项时匹配行将在首次出现处被合并。
长选项必须使用的参数对于短选项时也是必需使用的。
-c, --count 在每行前加上表示相应行目出现次数的前缀编号
-d, --repeated 只输出重复的行
-D, --all-repeated[=delimit-method 显示所有重复的行
delimit-method={none(
default
),prepend,separate} 以空行为界限
-f, --skip-fields=N 比较时跳过前N 列
-i, --ignore-
case
在比较的时候不区分大小写
-s, --skip-chars=N 比较时跳过前N 个字符
-u, --unique 只显示唯一的行
-z, --zero-terminated 使用
'\0'
作为行结束符,而不是新换行
-w, --check-chars=N 对每行第N 个字符以后的内容不作对照
--help 显示此帮助信息并退出
--version 显示版本信息并退出
若域中为先空字符(通常包括空格以及制表符),然后非空字符,域中字符前的空字符将被跳过。
提示:uniq 不会检查重复的行,除非它们是相邻的行。
如果您想先对输入排序,使用没有uniq 的
"sort -u"
。
删除重复行:
[root@xiaopeng ~]# uniq file.txt
[root@xiaopeng ~]# sort file.txt | uniq
[root@xiaopeng ~]# sort -u file.txt
只显示单一行:
[root@xiaopeng ~]# uniq -u file.txt
[root@xiaopeng ~]# sort file.txt | uniq -u
统计各行在文件中出现的次数:
[root@xiaopeng ~]# sort file.txt | uniq -c
在文件中找出重复的行:
[root@xiaopeng ~]# sort file.txt | uniq -dl
4.uniq命令用法演示
下面的命令删除了相邻的重复行,但是第一行111没有删除。
[root@xiaopeng ~]# uniq uniq.txt
111
223
56
111 # 删除了重复的111
567
223
排序后去重。
[root@xiaopeng ~]# sort uniq.txt | uniq
111
223
56
567
使用-d显示重复的行。
[root@xiaopeng ~]# sort uniq.txt | uniq -d
111
223
使用-D显示所有重复过的行。
[root@xiaopeng ~]# sort uniq.txt | uniq -D
111
111
111
223
223
使用-u显示唯一行。
[root@xiaopeng ~]# sort uniq.txt | uniq -u
56
567
使用-c统计哪些记录出现的次数。
[root@xiaopeng ~]# sort uniq.txt | uniq -c
3 111
2 223
1 56
1 567
使用-d -c统计重复行出现的次数。
[root@xiaopeng ~]# sort uniq.txt | uniq -d -c
3 111
2 223