1. 程式人生 > >Linux作業系統中sort命令詳解

Linux作業系統中sort命令詳解

sort是在Linux系統中很常用的一個命令,其功能和單詞本意相同,就是做排序的,不管是平時手工維護Linux系統,還是寫指令碼,這個命令一定大有用處,這篇文章將詳細介紹sort命令的引數及其含義。

1. sort的工作原理:sort將檔案的每一行作為一個單位,相互比較,比較原則是從首字元向後,依次按ASCII碼值進行比較,最後將他們按升序輸出。

  [[email protected]]$ cat seq.txt
  banana
  apple
  pear
  orange
  [[email protected]]$ sort seq.txt
  apple
  banana
  orange
  pear

2. sort的-u選項
它的作用很簡單,就是在輸出行中去除重複行。

  [[email protected]]$ cat seq.txt
  banana
  apple
  pear
  orange
  pear
  [[email protected]]$ sort seq.txt
  apple
  banana
  orange
  pear
  pear
  [[email protected]]$ sort -u seq.txt
  apple
  banana
  orange
  pear

pear由於重複被-u選項無情的刪除了。

3. sort的-r選項
sort預設的排序方式是升序,如果想改成降序,就加個-r就搞定了。

  [[email protected]]$ cat number.txt
  1
  3
  5
  2
  4
  [[email protected]]$ sort number.txt
  1
  2
  3
  4
  5
  [[email protected]]$ sort -r number.txt
  5
  4
  3
  2
  1

4. sort的-o選項
由於sort預設是把結果輸出到標準輸出,所以需要用重定向才能將結果寫入檔案,形如sort filename > newfile。
但是,如果你想把排序結果輸出到原檔案中,用重定向可就不行了。

  [[email protected]]$ sort -r number.txt > number.txt
  [[email protected]]$ cat number.txt
  [[[email protected]]$

汗,竟然將number清空了。
就在這個時候,-o選項出現了,它成功的解決了這個問題,讓你放心的將結果寫入原檔案。這或許也是-o比重定向的唯一優勢所在。

  [[email protected]]$ cat number.txt
  1
  3
  5
  2
  4
  [[email protected]]$ sort -r number.txt -o number.txt
  [[email protected]]$ cat number.txt
  5
  4
  3
  2
  1

5. sort的-n選項
你有沒有遇到過10比2小的情況。我反正遇到過。出現這種情況是由於排序程式將這些數字按字元來排序了,排序程式會先比較1和2,顯然1小,所以就將10放在2前面嘍。這也是sort的一貫作風。
我們如果想改變這種現狀,就要使用-n選項,來告訴sort,“要以數值來排序”!

  [[email protected]]$ cat number.txt
  1
  10
  19
  11
  2
  5
  [[email protected]]$ sort number.txt
  1
  10
  11
  19
  2
  5
  [[email protected]]$ sort -n number.txt
  1
  2
  5
  10
  11
  19

6. sort的-t選項和-k選項,如果有一個檔案的內容是這樣:

  [[email protected]]$ cat facebook.txt
  banana:30:5.5
  apple:10:2.5
  pear:90:2.3
  orange:20:3.4

這個檔案有三列,列與列之間用冒號隔開了,第一列表示水果型別,第二列表示水果數量,第三列表示水果價格。
那麼我想以水果數量來排序,也就是以第二列來排序,如何利用sort實現?
幸好,sort提供了-t選項,後面可以設定間隔符。(是不是想起了cut和paste的-d選項,共鳴~~)
指定了間隔符之後,就可以用-k來指定列數了。

  [[email protected]]$ sort -n -k 2 -t : facebook.txt
  apple:10:2.5
  orange:20:3.4
  banana:30:5.5
  pear:90:2.3

我們使用冒號作為間隔符,並針對第二列來進行數值升序排序,結果很令人滿意。

7. 其它的sort常用選項:
-f會將小寫字母都轉換為大寫字母來進行比較,亦即忽略大小寫
-c會檢查檔案是否已排好序,如果亂序,則輸出第一個亂序的行的相關資訊,最後返回1
-C會檢查檔案是否已排好序,如果亂序,不輸出內容,僅返回1
-M會以月份來排序,比如JAN小於FEB等等
-b會忽略每一行前面的所有空白部分,從第一個可見字元開始比較。