Shell learns sort, cut, uniq for file operations

In the process of using the Linux system, we often need to perform some operational analysis on the file, such as classifying and sorting the text, removing duplicates, and intercepting some regularized fields. cut, sort, uniq is very convenient to use.

1.sort: There are generally three modes, namely sorting text, checking files, and merging files.

常用方法及参数
sort [option] [file]
  -b,#忽略前空格或者制表符
  -d, #根据字典顺序排序,仅比较数字,字母和空字符
  -f, #忽略大小写
  -i, #仅仅比较可打印文件
  -n, #根据算术值比较,空格,十进制数字等。
  -R, #根据哈希值随机排序
  -r, #颠倒排序结果
  -u,#删除重复的行,只保留一个文件
[root@node-2 home]# cat text
1
1
2
2
3
4
3
33
5
1
44
11
5
6
7
8
A
9
11
10
11
[root@node-2 home]# sort text #默认比较首个字符的hash值来排序
1
1
1
10
11
11
11
2
2
3
3
33
4
44
5
5
6
7
8
9
A
[root@node-2 home]# sort -n text #按照数值排列
A
1
1
1
2
2
3
3
4
5
5
6
7
8
9
10
11
11
11
33
44
[root@node-2 home]# sort -nr text #倒序
44
33
11
11
11
10
9
8
7
6
5
5
4
3
3
2
2
1
1
1
A
[root@node-2 home]# sort -R text #随机排序
44
7
8
1
1
1
9
2
2
11
11
11
A
5
5
3
3
33
10
6
4

2.cut command: Sometimes the files are arranged in a regular order. We need to take out one or several columns of data, and we can use the cut command to select parts from the vertical direction.

常用方法及参数:
cut options [file]
 -d #自定义分隔符
 -c #只选择指定字符
 -f #只选择列表中指定的文本列,文本列用列号表示,多个列用逗号隔开
 -s #不输出不包含列分隔符的行
例子:查看/etc/passwd文件,取出所有的用户以及对应的uid,gid以及家目录
[root@node-2 home]# cut -d":" -f 1,3,4,7  /etc/passwd|head -n10
root:0:0:/bin/bash
bin:1:1:/sbin/nologin
daemon:2:2:/sbin/nologin
adm:3:4:/sbin/nologin
lp:4:7:/sbin/nologin
sync:5:0:/bin/sync
shutdown:6:0:/sbin/shutdown
halt:7:0:/sbin/halt
mail:8:12:/sbin/nologin
uucp:10:14:/sbin/nologin
[root@node-2 home]# 

3.uniq: The uniq command is used to check and delete repeated rows and columns in text files

 -c # 在每列旁边显示该行重复出现的次数。
 -d #仅显示重复出现的行列。
 -u #仅显示出一次的行列
 --help  #显示帮助。
 --version  #显示版本信息。
[root@node-2 home]# sort -n text
A
1
1
1
2
2
3
3
4
5
5
6
7
8
9
10
11
11
11
33
44

[root@node-2 home]# sort -n text|uniq -c #显示出现的次数
      1 A
      3 1
      2 2
      2 3
      1 4
      2 5
      1 6
      1 7
      1 8
      1 9
      1 10
      3 11
      1 33
      1 44
[root@node-2 home]# sort -n text|uniq -u #显示只出现过一次的
A
4
6
7
8
9
10
33
44
[root@node-2 home]# sort -n text|uniq -d #显示重复出现的
1
2
3
5
11
[root@node-2 home]# 
生成一个55以内的随机数
[root@node-2 home]# seq 55|sort -R|head -1
4

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324653423&siteId=291194637