linux sort命令学习
linux sort命令以行为单位对文本文件进行排序。
接下来我们会以/tmp/sort_test.txt这个文本文件为例对sort命令的用法进行说明。
sh-# cat /tmp/sort_test.txt
10 my name is xulin
2 I like programming
3 what about you?
sh-#
1. 因为sort命令是按照字符比较的方式进行排序,所以便出现以下的结果,
sh-# cat /tmp/sort_test.txt | sort
10 my name is xulin
2 I like programming
3 what about you?
sh-#
2. 指定-n选项,这样就会以字符串数值大小进行排序,
sh-# cat /tmp/sort_test.txt | sort -n
2 I like programming
3 what about you?
10 my name is xulin
sh-#
3. 如果要反向排序,那就要指定-r选项了,
sh-# cat /tmp/sort_test.txt | sort -nr
10 my name is xulin
3 what about you?
2 I like programming
sh-#
4. 有时候用户希望能够按字段进行排序,其中-t选项用来指定域分隔符,-k用来指定位置,
sh-# cat /tmp/sort_test.txt | sort -t' ' -k 1,2
10 my name is xulin
2 I like programming
3 what about you?
sh-#
sh-# cat /tmp/sort_test.txt | sort -t' ' -k 2,3
2 I like programming
10 my name is xulin
3 what about you?
sh-#
sh-# ifconfig lo
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:9 errors:0 dropped:0 overruns:0 frame:0
TX packets:9 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:456 (456.0 b) TX bytes:456 (456.0 b)
sh-#
sh-# ifconfig lo | sort
RX bytes:456 (456.0 b) TX bytes:456 (456.0 b)
RX packets:9 errors:0 dropped:0 overruns:0 frame:0
TX packets:9 errors:0 dropped:0 overruns:0 carrier:0
UP LOOPBACK RUNNING MTU:16436 Metric:1
collisions:0 txqueuelen:0
inet addr:127.0.0.1 Mask:255.0.0.0
lo Link encap:Local Loopback
sh-#
sh-# ifconfig lo | sort -t: -k 2 -n
collisions:0 txqueuelen:0
lo Link encap:Local Loopback
RX packets:9 errors:0 dropped:0 overruns:0 frame:0
TX packets:9 errors:0 dropped:0 overruns:0 carrier:0
inet addr:127.0.0.1 Mask:255.0.0.0
RX bytes:456 (456.0 b) TX bytes:456 (456.0 b)
UP LOOPBACK RUNNING MTU:16436 Metric:1
sh-#
sh-# ifconfig lo | sort -t: -k 2 -nr
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX bytes:456 (456.0 b) TX bytes:456 (456.0 b)
inet addr:127.0.0.1 Mask:255.0.0.0
TX packets:9 errors:0 dropped:0 overruns:0 carrier:0
RX packets:9 errors:0 dropped:0 overruns:0 frame:0
lo Link encap:Local Loopback
collisions:0 txqueuelen:0
sh-#
是不是很方便呢?