如何在Linux中就地排序檔案?


為了能夠在Linux中對檔案內容進行排序,我們首先必須瞭解Linux提供的**sort**命令。

sort命令主要用於對檔案內容進行排序。它以特定方式排列記錄。預設情況下,這些記錄的排序是基於ASCII值。

關於sort命令,需要記住以下幾點:

  • **SORT**命令一次對一行進行排序。

  • 當用於檔案時,它會像**cat**命令一樣列印檔案的內容。

  • 它通常忽略大小寫。

語法

sort filename

現在我們對sort命令有所瞭解,讓我們來使用它。請考慮以下幾個示例。

示例1

排序前的檔案內容按此順序排列。

immukul@192 d1 % cat somefile.txt
Is this text added
this file contains
a new text stream
and i am going to edit
that stream
yes i can do that
ask jeffrey

命令

sort filename.txt

輸出

immukul@192 d1 % sort somefile.txt
Is this text added
a new text stream
and i am going to edit
ask jeffrey
that stream
this file contains
yes i can do that

我們可以看到,輸出是基於ASCII編碼排序的。

需要注意的是,輸出肯定是排序後的,但檔案的內容不會改變,我們可以使用cat命令再次列印檔案內容來確認這一點。

immukul@192 d1 % cat somefile.txt
Is this text added
this file contains
a new text stream
and i am going to edit
that stream
yes i can do that
ask jeffrey

為了真正改變檔案的內容,可以使用以下命令。

sort somefile.txt > anotherfile.txt

輸出

immukul@192 d1 % cat anotherfile.txt
Is this text added
a new text stream
and i am going to edit
ask jeffrey
that stream
this file contains
yes i can do that

更新於:2021年7月31日

1K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.