利用Linux命令列進行文本按行去重並按重複次數排序 linux命令列提供了非常強大的文本處理功能,組合利用linux命令能實現好多強大的功能。本文這裡舉例說明如何利用Linux命令列進行文本按行去重並按重複次數排序。主要用到的命令有sort,uniq和cut。其中,sort主要功能是排序,uniq主要功能是實現相鄰文本行的去重,cut可以從文本行中提取相應的文本列(簡單地說,就是按列操作文本行)。 用於示範的測試檔案內容如下: [plain] Hello World. Apple and Nokia. Hello World. I wanna buy an Apple device. The Iphone of Apple company. Hello World. The Iphone of Apple company. My name is Friendfish. Hello World. Apple and Nokia. 實現命令及過程如下:[plain] 1、文本行去重 (1)排序 由於uniq命令只能對相鄰行進行去重複操作,所以在進行去重前,先要對文本行進行排序,使重複行集中到一起。 $ sort test.txt Apple and Nokia. Apple and Nokia. Hello World. Hello World. Hello World. Hello World. I wanna buy an Apple device. My name is Friendfish. The Iphone of Apple company. The Iphone of Apple company. (2)去掉相鄰的重複行 $ sort test.txt | uniq Apple and Nokia. Hello World. I wanna buy an Apple device. My name is Friendfish. The Iphone of Apple company. 2、文本行去重並按重複次數排序 (1)首先,對文本行進行去重並統計重複次數(uniq命令加-c選項可以實現對重複次數進行統計。)。 $ sort test.txt | uniq -c 2 Apple and Nokia. 4 Hello World. 1 I wanna buy an Apple device. 1 My name is Friendfish. 2 The Iphone of Apple company. (2)對文本行按重複次數進行排序。 sort -n可以識別每行開頭的數字,並按其大小對文本行進行排序。預設是按升序排列,如果想要按降序要加-r選項(sort -rn)。 $ sort test.txt | uniq -c | sort -rn 4 Hello World. 2 The Iphone of Apple company. 2 Apple and Nokia. 1 My name is Friendfish. 1 I wanna buy an Apple device. (3)每行前面的重複資料刪除次數。 cut命令可以按列操作文本行。可以看出前面的重複次數佔8個字元,因此,可以用命令cut -c 9- 取出每行第9個及其以後的字元。 $ sort test.txt | uniq -c | sort -rn | cut -c 9- Hello World. The Iphone of Apple company. Apple and Nokia. My name is Friendfish. I wanna buy an Apple device. 下面附帶說一下cut命令的使用,用法如下: [plain] cut -b list [-n] [file ...] cut -c list [file ...] cut -f list [-d delim][-s][file ...] 上面的-b、-c、-f分別表示位元組、字元、欄位(即byte、character、field); list表示-b、-c、-f操作範圍,-n常常表示具體數字; file表示的自然是要操作的文字檔的名稱; delim(英文全寫:delimiter)表示分隔字元,預設情況下為TAB; -s表示不包括那些不含分隔字元的行(這樣有利於去掉注釋和標題) 三種方式中,表示從指定的範圍中提取位元組(-b)、或字元(-c)、或欄位(-f)。 範圍的表示方法: n 只有第n項 n- 從第n項一直到行尾 n-m 從第n項到第m項(包括m) -m 從一行的開始到第m項(包括m) - 從一行的開始到結束的所有項 在寫這篇文章的時候,用到了vim的大小寫轉化的快速鍵:gu變小寫,gU變大寫。結合ctrl+v能夠將一片文字中的字元進行大小寫轉換,非常好用。