Sorting File Contents and Output with sort

时间:2021-07-12 16:50:40

 Sorting File Contents and Output with sort  

Another very useful command to use on text file is  sort . As you can probably guess, this command sorts text. If you type  sort /etc/passwd , for instance, the content of the /etc/passwd file is sorted in alphabetic order. You can use the  sort  command on the output of a command also, as in  cut -f 1 -d : /etc/passwd | sort , which sorts the contents of the first column in the /etc/passwd file.

[root@rhel7 ~]# cut -f  -d : /etc/passwd
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
operator
games
ftp
nobody
avahi-autoipd
systemd-bus-proxy
systemd-network
dbus
polkitd
tss
postfix
sshd
rusky
[root@rhel7 ~]# cut -f -d : /etc/passwd | sort
adm
avahi-autoipd
bin
daemon
dbus
ftp
games
halt
lp
mail
nobody
operator
polkitd
postfix
root
rusky
shutdown
sshd
sync
systemd-bus-proxy
systemd-network
tss

By default, the  sort  command sorts in alphabetic order(默认是以阿尔法字母排序). In some cases, that is not convenient because the content that needs sorting may be numeric or in another format. The  sort  command offers different options to help sorting these specific types of data. Type, for instance,  cut -f 3 -d : /etc/passwd | sort -n  to sort the third field of the /etc/passwd file in numeric order.(使用sort -n 参数来按数字进行排序)

[root@rhel7 ~]# cut -f  -d : /etc/passwd 

[root@rhel7 ~]# cut -f  -d : /etc/passwd |sort -n

It can be useful also to sort in reverse order; if you use the command  du -h | sort -rn , you get a list of files sorted with the biggest file in that directory listed first. (按倒序排序)

[root@rhel7 ~]# cut -f  -d : /etc/passwd |sort -rn

You can also use the  sort  command and specify which column you want to sort. To do this, use  sort -k3 -t : /etc/passwd , for instance, which uses the field separator : to sort the third column of the /etc/passwd file.   (按第三列进行排序,-t指定分隔符为:)

[root@rhel7 ~]# sort -k3 -t : /etc/passwd
root:x:::root:/root:/bin/bash
rusky:x:::rusky:/home/rusky:/bin/bash
operator:x:::operator:/root:/sbin/nologin
bin:x:::bin:/bin:/sbin/nologin
games:x:::games:/usr/games:/sbin/nologin
ftp:x:::FTP User:/var/ftp:/sbin/nologin
avahi-autoipd:x:::Avahi IPv4LL Stack:/var/lib/avahi-autoipd:/sbin/nologin
daemon:x:::daemon:/sbin:/sbin/nologin
adm:x:::adm:/var/adm:/sbin/nologin
lp:x:::lp:/var/spool/lpd:/sbin/nologin
sync:x:::sync:/sbin:/bin/sync
tss:x:::Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
shutdown:x:::shutdown:/sbin:/sbin/shutdown
halt:x:::halt:/sbin:/sbin/halt
sshd:x:::Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
mail:x:::mail:/var/spool/mail:/sbin/nologin
dbus:x:::System message bus:/:/sbin/nologin
postfix:x::::/var/spool/postfix:/sbin/nologin
polkitd:x:::User for polkitd:/:/sbin/nologin
systemd-network:x:::systemd Network Management:/:/sbin/nologin
systemd-bus-proxy:x:::systemd Bus Proxy:/:/sbin/nologin
nobody:x:::Nobody:/:/sbin/nologin
[root@rhel7 ~]#